2
0

DnsInterceptor.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. /// <returns></returns>
  54. public async Task InterceptAsync(CancellationToken cancellationToken)
  55. {
  56. await Task.Yield();
  57. var handle = WinDivert.WinDivertOpen(DNS_FILTER, WinDivertLayer.Network, 0, WinDivertOpenFlags.None);
  58. if (handle == IntPtr.MaxValue || handle == IntPtr.Zero)
  59. {
  60. this.logger.LogError($"打开驱动失败");
  61. return;
  62. }
  63. cancellationToken.Register(hwnd =>
  64. {
  65. WinDivert.WinDivertClose((IntPtr)hwnd!);
  66. DnsFlushResolverCache();
  67. }, handle);
  68. var packetLength = 0U;
  69. using var winDivertBuffer = new WinDivertBuffer();
  70. var winDivertAddress = new WinDivertAddress();
  71. DnsFlushResolverCache();
  72. while (cancellationToken.IsCancellationRequested == false)
  73. {
  74. if (WinDivert.WinDivertRecv(handle, winDivertBuffer, ref winDivertAddress, ref packetLength))
  75. {
  76. try
  77. {
  78. this.ModifyDnsPacket(winDivertBuffer, ref winDivertAddress, ref packetLength);
  79. }
  80. catch (Exception ex)
  81. {
  82. this.logger.LogWarning(ex.Message);
  83. }
  84. finally
  85. {
  86. WinDivert.WinDivertSend(handle, winDivertBuffer, packetLength, ref winDivertAddress);
  87. }
  88. }
  89. else
  90. {
  91. var exception = new Win32Exception(Marshal.GetLastWin32Error());
  92. this.logger.LogError(exception.Message);
  93. }
  94. }
  95. }
  96. /// <summary>
  97. /// 修改DNS数据包
  98. /// </summary>
  99. /// <param name="winDivertBuffer"></param>
  100. /// <param name="winDivertAddress"></param>
  101. /// <param name="packetLength"></param>
  102. unsafe private void ModifyDnsPacket(WinDivertBuffer winDivertBuffer, ref WinDivertAddress winDivertAddress, ref uint packetLength)
  103. {
  104. var packet = WinDivert.WinDivertHelperParsePacket(winDivertBuffer, packetLength);
  105. var requestPayload = new Span<byte>(packet.PacketPayload, (int)packet.PacketPayloadLength).ToArray();
  106. if (TryParseRequest(requestPayload, out var request) == false ||
  107. request.OperationCode != OperationCode.Query ||
  108. request.Questions.Count == 0)
  109. {
  110. return;
  111. }
  112. var question = request.Questions.First();
  113. if (question.Type != RecordType.A)
  114. {
  115. return;
  116. }
  117. var domain = question.Name;
  118. if (this.fastGithubConfig.IsMatch(question.Name.ToString()) == false)
  119. {
  120. return;
  121. }
  122. // dns响应数据
  123. var response = Response.FromRequest(request);
  124. var record = new IPAddressResourceRecord(domain, IPAddress.Loopback, this.ttl);
  125. response.AnswerRecords.Add(record);
  126. var responsePayload = response.ToArray();
  127. // 修改payload和包长
  128. responsePayload.CopyTo(new Span<byte>(packet.PacketPayload, responsePayload.Length));
  129. packetLength = (uint)((int)packetLength + responsePayload.Length - requestPayload.Length);
  130. // 修改ip包
  131. if (packet.IPv4Header != null)
  132. {
  133. var destAddress = packet.IPv4Header->DstAddr;
  134. packet.IPv4Header->DstAddr = packet.IPv4Header->SrcAddr;
  135. packet.IPv4Header->SrcAddr = destAddress;
  136. packet.IPv4Header->Length = BinaryPrimitives.ReverseEndianness((ushort)packetLength);
  137. }
  138. else
  139. {
  140. var destAddress = packet.IPv6Header->DstAddr;
  141. packet.IPv6Header->DstAddr = packet.IPv6Header->SrcAddr;
  142. packet.IPv6Header->SrcAddr = destAddress;
  143. packet.IPv6Header->Length = BinaryPrimitives.ReverseEndianness((ushort)packetLength);
  144. }
  145. // 修改udp包
  146. var destPort = packet.UdpHeader->DstPort;
  147. packet.UdpHeader->DstPort = packet.UdpHeader->SrcPort;
  148. packet.UdpHeader->SrcPort = destPort;
  149. packet.UdpHeader->Length = BinaryPrimitives.ReverseEndianness((ushort)(sizeof(UdpHeader) + responsePayload.Length));
  150. // 反转方向
  151. winDivertAddress.Impostor = true;
  152. if (winDivertAddress.Direction == WinDivertDirection.Inbound)
  153. {
  154. winDivertAddress.Direction = WinDivertDirection.Outbound;
  155. }
  156. else
  157. {
  158. winDivertAddress.Direction = WinDivertDirection.Inbound;
  159. }
  160. WinDivert.WinDivertHelperCalcChecksums(winDivertBuffer, packetLength, ref winDivertAddress, WinDivertChecksumHelperParam.All);
  161. this.logger.LogInformation($"{domain} => {IPAddress.Loopback}");
  162. }
  163. /// <summary>
  164. /// 尝试解析请求
  165. /// </summary>
  166. /// <param name="payload"></param>
  167. /// <param name="request"></param>
  168. /// <returns></returns>
  169. static bool TryParseRequest(byte[] payload, [MaybeNullWhen(false)] out Request request)
  170. {
  171. try
  172. {
  173. request = Request.FromArray(payload);
  174. return true;
  175. }
  176. catch (Exception)
  177. {
  178. request = null;
  179. return false;
  180. }
  181. }
  182. }
  183. }