DnsInterceptor.cs 7.0 KB

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