DnsInterceptor.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. using DNS.Protocol;
  2. using DNS.Protocol.ResourceRecords;
  3. using FastGithub.Configuration;
  4. using FastGithub.DomainResolve;
  5. using FastGithub.WinDiverts;
  6. using Microsoft.Extensions.Logging;
  7. using Microsoft.Extensions.Options;
  8. using System;
  9. using System.ComponentModel;
  10. using System.Diagnostics.CodeAnalysis;
  11. using System.Linq;
  12. using System.Net;
  13. using System.Runtime.InteropServices;
  14. using System.Runtime.Versioning;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  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 IDomainResolver domainResolver;
  28. private readonly ILogger<DnsInterceptor> logger;
  29. private readonly TimeSpan ttl = TimeSpan.FromMinutes(10d);
  30. /// <summary>
  31. /// 刷新DNS缓存
  32. /// </summary>
  33. [DllImport("dnsapi.dll", EntryPoint = "DnsFlushResolverCache", SetLastError = true)]
  34. private static extern void DnsFlushResolverCache();
  35. /// <summary>
  36. /// dns拦截器
  37. /// </summary>
  38. /// <param name="fastGithubConfig"></param>
  39. /// <param name="domainResolver"></param>
  40. /// <param name="logger"></param>
  41. /// <param name="options"></param>
  42. public DnsInterceptor(
  43. FastGithubConfig fastGithubConfig,
  44. IDomainResolver domainResolver,
  45. ILogger<DnsInterceptor> logger,
  46. IOptionsMonitor<FastGithubOptions> options)
  47. {
  48. this.fastGithubConfig = fastGithubConfig;
  49. this.logger = logger;
  50. this.domainResolver = domainResolver;
  51. options.OnChange(_ => DnsFlushResolverCache());
  52. }
  53. /// <summary>
  54. /// DNS拦截
  55. /// </summary>
  56. /// <param name="cancellationToken"></param>
  57. /// <exception cref="Win32Exception"></exception>
  58. /// <returns></returns>
  59. public async Task InterceptAsync(CancellationToken cancellationToken)
  60. {
  61. await Task.Yield();
  62. var handle = WinDivert.WinDivertOpen(DNS_FILTER, WinDivertLayer.Network, 0, WinDivertOpenFlags.None);
  63. if (handle == new IntPtr(unchecked((long)ulong.MaxValue)))
  64. {
  65. throw new Win32Exception();
  66. }
  67. cancellationToken.Register(hwnd =>
  68. {
  69. WinDivert.WinDivertClose((IntPtr)hwnd!);
  70. DnsFlushResolverCache();
  71. }, handle);
  72. var packetLength = 0U;
  73. using var winDivertBuffer = new WinDivertBuffer();
  74. var winDivertAddress = new WinDivertAddress();
  75. DnsFlushResolverCache();
  76. while (cancellationToken.IsCancellationRequested == false)
  77. {
  78. if (WinDivert.WinDivertRecv(handle, winDivertBuffer, ref winDivertAddress, ref packetLength) == false)
  79. {
  80. throw new Win32Exception();
  81. }
  82. try
  83. {
  84. this.ModifyDnsPacket(winDivertBuffer, ref winDivertAddress, ref packetLength);
  85. }
  86. catch (Exception ex)
  87. {
  88. this.logger.LogWarning(ex.Message);
  89. }
  90. finally
  91. {
  92. WinDivert.WinDivertSend(handle, winDivertBuffer, packetLength, ref winDivertAddress);
  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. this.domainResolver.Prefetch(domain.ToString());
  124. // dns响应数据
  125. var response = Response.FromRequest(request);
  126. var record = new IPAddressResourceRecord(domain, IPAddress.Loopback, this.ttl);
  127. response.AnswerRecords.Add(record);
  128. var responsePayload = response.ToArray();
  129. // 修改payload和包长
  130. responsePayload.CopyTo(new Span<byte>(packet.PacketPayload, responsePayload.Length));
  131. packetLength = (uint)((int)packetLength + responsePayload.Length - requestPayload.Length);
  132. // 修改ip包
  133. if (packet.IPv4Header != null)
  134. {
  135. var destAddress = packet.IPv4Header->DstAddr;
  136. packet.IPv4Header->DstAddr = packet.IPv4Header->SrcAddr;
  137. packet.IPv4Header->SrcAddr = destAddress;
  138. packet.IPv4Header->Length = (ushort)packetLength;
  139. }
  140. else
  141. {
  142. var destAddress = packet.IPv6Header->DstAddr;
  143. packet.IPv6Header->DstAddr = packet.IPv6Header->SrcAddr;
  144. packet.IPv6Header->SrcAddr = destAddress;
  145. packet.IPv6Header->Length = (ushort)packetLength;
  146. }
  147. // 修改udp包
  148. var destPort = packet.UdpHeader->DstPort;
  149. packet.UdpHeader->DstPort = packet.UdpHeader->SrcPort;
  150. packet.UdpHeader->SrcPort = destPort;
  151. packet.UdpHeader->Length = (ushort)(sizeof(UdpHeader) + responsePayload.Length);
  152. winDivertAddress.Impostor = true;
  153. WinDivert.WinDivertHelperCalcChecksums(winDivertBuffer, packetLength, ref winDivertAddress, WinDivertChecksumHelperParam.All);
  154. }
  155. /// <summary>
  156. /// 尝试解析请求
  157. /// </summary>
  158. /// <param name="payload"></param>
  159. /// <param name="request"></param>
  160. /// <returns></returns>
  161. static bool TryParseRequest(byte[] payload, [MaybeNullWhen(false)] out Request request)
  162. {
  163. try
  164. {
  165. request = Request.FromArray(payload);
  166. return true;
  167. }
  168. catch (Exception)
  169. {
  170. request = null;
  171. return false;
  172. }
  173. }
  174. }
  175. }