DnsInterceptor.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. using DNS.Protocol;
  2. using DNS.Protocol.ResourceRecords;
  3. using FastGithub.Configuration;
  4. using FastGithub.WinDiverts;
  5. using Microsoft.Extensions.Logging;
  6. using Microsoft.Extensions.Options;
  7. using System;
  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. 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(1d);
  28. /// <summary>
  29. /// 刷新DNS缓存
  30. /// </summary>
  31. [DllImport("dnsapi.dll", EntryPoint = "DnsFlushResolverCache", SetLastError = true)]
  32. private static extern void DnsFlushResolverCache();
  33. /// <summary>
  34. /// 首次加载驱动往往有异常,所以要提前加载
  35. /// </summary>
  36. static DnsInterceptor()
  37. {
  38. var handle = WinDivert.WinDivertOpen("false", WinDivertLayer.Network, 0, WinDivertOpenFlags.None);
  39. WinDivert.WinDivertClose(handle);
  40. }
  41. /// <summary>
  42. /// dns拦截器
  43. /// </summary>
  44. /// <param name="fastGithubConfig"></param>
  45. /// <param name="logger"></param>
  46. /// <param name="options"></param>
  47. public DnsInterceptor(
  48. FastGithubConfig fastGithubConfig,
  49. ILogger<DnsInterceptor> logger,
  50. IOptionsMonitor<FastGithubOptions> options)
  51. {
  52. this.fastGithubConfig = fastGithubConfig;
  53. this.logger = logger;
  54. options.OnChange(_ => DnsFlushResolverCache());
  55. }
  56. /// <summary>
  57. /// DNS拦截
  58. /// </summary>
  59. /// <param name="cancellationToken"></param>
  60. /// <exception cref="Win32Exception"></exception>
  61. /// <returns></returns>
  62. public async Task InterceptAsync(CancellationToken cancellationToken)
  63. {
  64. await Task.Yield();
  65. var handle = WinDivert.WinDivertOpen(DNS_FILTER, WinDivertLayer.Network, 0, WinDivertOpenFlags.None);
  66. if (handle == new IntPtr(unchecked((long)ulong.MaxValue)))
  67. {
  68. throw new Win32Exception();
  69. }
  70. cancellationToken.Register(hwnd =>
  71. {
  72. WinDivert.WinDivertClose((IntPtr)hwnd!);
  73. DnsFlushResolverCache();
  74. }, handle);
  75. var packetLength = 0U;
  76. using var winDivertBuffer = new WinDivertBuffer();
  77. var winDivertAddress = new WinDivertAddress();
  78. DnsFlushResolverCache();
  79. while (cancellationToken.IsCancellationRequested == false)
  80. {
  81. if (WinDivert.WinDivertRecv(handle, winDivertBuffer, ref winDivertAddress, ref packetLength) == false)
  82. {
  83. throw new Win32Exception();
  84. }
  85. try
  86. {
  87. this.ModifyDnsPacket(winDivertBuffer, ref winDivertAddress, ref packetLength);
  88. }
  89. catch (Exception ex)
  90. {
  91. this.logger.LogWarning(ex.Message);
  92. }
  93. finally
  94. {
  95. WinDivert.WinDivertSend(handle, winDivertBuffer, packetLength, ref winDivertAddress);
  96. }
  97. }
  98. }
  99. /// <summary>
  100. /// 修改DNS数据包
  101. /// </summary>
  102. /// <param name="winDivertBuffer"></param>
  103. /// <param name="winDivertAddress"></param>
  104. /// <param name="packetLength"></param>
  105. unsafe private void ModifyDnsPacket(WinDivertBuffer winDivertBuffer, ref WinDivertAddress winDivertAddress, ref uint packetLength)
  106. {
  107. var packet = WinDivert.WinDivertHelperParsePacket(winDivertBuffer, packetLength);
  108. var requestPayload = new Span<byte>(packet.PacketPayload, (int)packet.PacketPayloadLength).ToArray();
  109. if (TryParseRequest(requestPayload, out var request) == false ||
  110. request.OperationCode != OperationCode.Query ||
  111. request.Questions.Count == 0)
  112. {
  113. return;
  114. }
  115. var question = request.Questions.First();
  116. if (question.Type != RecordType.A && question.Type != RecordType.AAAA)
  117. {
  118. return;
  119. }
  120. var domain = question.Name;
  121. if (this.fastGithubConfig.IsMatch(question.Name.ToString()) == false)
  122. {
  123. return;
  124. }
  125. // dns响应数据
  126. var response = Response.FromRequest(request);
  127. if (question.Type == RecordType.A)
  128. {
  129. var record = new IPAddressResourceRecord(domain, IPAddress.Loopback, this.ttl);
  130. response.AnswerRecords.Add(record);
  131. this.logger.LogInformation($"{domain}->{IPAddress.Loopback}");
  132. }
  133. else
  134. {
  135. this.logger.LogInformation($"{domain}->NULL");
  136. }
  137. var responsePayload = response.ToArray();
  138. // 修改payload和包长
  139. responsePayload.CopyTo(new Span<byte>(packet.PacketPayload, responsePayload.Length));
  140. packetLength = (uint)((int)packetLength + responsePayload.Length - requestPayload.Length);
  141. // 修改ip包
  142. IPAddress destAddress;
  143. if (packet.IPv4Header != null)
  144. {
  145. destAddress = packet.IPv4Header->DstAddr;
  146. packet.IPv4Header->DstAddr = packet.IPv4Header->SrcAddr;
  147. packet.IPv4Header->SrcAddr = destAddress;
  148. packet.IPv4Header->Length = (ushort)packetLength;
  149. }
  150. else
  151. {
  152. destAddress = packet.IPv6Header->DstAddr;
  153. packet.IPv6Header->DstAddr = packet.IPv6Header->SrcAddr;
  154. packet.IPv6Header->SrcAddr = destAddress;
  155. packet.IPv6Header->Length = (ushort)packetLength;
  156. }
  157. // 修改udp包
  158. var destPort = packet.UdpHeader->DstPort;
  159. packet.UdpHeader->DstPort = packet.UdpHeader->SrcPort;
  160. packet.UdpHeader->SrcPort = destPort;
  161. packet.UdpHeader->Length = (ushort)(sizeof(UdpHeader) + responsePayload.Length);
  162. winDivertAddress.Impostor = true;
  163. winDivertAddress.Direction = winDivertAddress.Loopback
  164. ? WinDivertDirection.Outbound
  165. : WinDivertDirection.Inbound;
  166. WinDivert.WinDivertHelperCalcChecksums(winDivertBuffer, packetLength, ref winDivertAddress, WinDivertChecksumHelperParam.All);
  167. }
  168. /// <summary>
  169. /// 尝试解析请求
  170. /// </summary>
  171. /// <param name="payload"></param>
  172. /// <param name="request"></param>
  173. /// <returns></returns>
  174. static bool TryParseRequest(byte[] payload, [MaybeNullWhen(false)] out Request request)
  175. {
  176. try
  177. {
  178. request = Request.FromArray(payload);
  179. return true;
  180. }
  181. catch (Exception)
  182. {
  183. request = null;
  184. return false;
  185. }
  186. }
  187. }
  188. }