DnsInterceptor.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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 int ERROR_INVALID_HANDLE = 0x6;
  26. private const string DNS_FILTER = "udp.DstPort == 53";
  27. private readonly FastGithubConfig fastGithubConfig;
  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="logger"></param>
  40. /// <param name="options"></param>
  41. public DnsInterceptor(
  42. FastGithubConfig fastGithubConfig,
  43. ILogger<DnsInterceptor> logger,
  44. IOptionsMonitor<FastGithubOptions> options)
  45. {
  46. this.fastGithubConfig = fastGithubConfig;
  47. this.logger = logger;
  48. options.OnChange(_ => DnsFlushResolverCache());
  49. }
  50. /// <summary>
  51. /// DNS拦截
  52. /// </summary>
  53. /// <param name="cancellationToken"></param>
  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. this.logger.LogError($"打开驱动失败");
  62. return;
  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))
  76. {
  77. try
  78. {
  79. this.ModifyDnsPacket(winDivertBuffer, ref winDivertAddress, ref packetLength);
  80. }
  81. catch (Exception ex)
  82. {
  83. this.logger.LogWarning(ex.Message);
  84. }
  85. finally
  86. {
  87. WinDivert.WinDivertSend(handle, winDivertBuffer, packetLength, ref winDivertAddress);
  88. }
  89. }
  90. else
  91. {
  92. var errorCode = Marshal.GetLastWin32Error();
  93. this.logger.LogError(new Win32Exception(errorCode).Message);
  94. if (errorCode == ERROR_INVALID_HANDLE)
  95. {
  96. break;
  97. }
  98. }
  99. }
  100. }
  101. /// <summary>
  102. /// 修改DNS数据包
  103. /// </summary>
  104. /// <param name="winDivertBuffer"></param>
  105. /// <param name="winDivertAddress"></param>
  106. /// <param name="packetLength"></param>
  107. unsafe private void ModifyDnsPacket(WinDivertBuffer winDivertBuffer, ref WinDivertAddress winDivertAddress, ref uint packetLength)
  108. {
  109. var packet = WinDivert.WinDivertHelperParsePacket(winDivertBuffer, packetLength);
  110. var requestPayload = new Span<byte>(packet.PacketPayload, (int)packet.PacketPayloadLength).ToArray();
  111. if (TryParseRequest(requestPayload, out var request) == false ||
  112. request.OperationCode != OperationCode.Query ||
  113. request.Questions.Count == 0)
  114. {
  115. return;
  116. }
  117. var question = request.Questions.First();
  118. if (question.Type != RecordType.A)
  119. {
  120. return;
  121. }
  122. var domain = question.Name;
  123. if (this.fastGithubConfig.IsMatch(question.Name.ToString()) == false)
  124. {
  125. return;
  126. }
  127. // dns响应数据
  128. var response = Response.FromRequest(request);
  129. var record = new IPAddressResourceRecord(domain, IPAddress.Loopback, this.ttl);
  130. response.AnswerRecords.Add(record);
  131. var responsePayload = response.ToArray();
  132. // 修改payload和包长
  133. responsePayload.CopyTo(new Span<byte>(packet.PacketPayload, responsePayload.Length));
  134. packetLength = (uint)((int)packetLength + responsePayload.Length - requestPayload.Length);
  135. // 修改ip包
  136. if (packet.IPv4Header != null)
  137. {
  138. var destAddress = packet.IPv4Header->DstAddr;
  139. packet.IPv4Header->DstAddr = packet.IPv4Header->SrcAddr;
  140. packet.IPv4Header->SrcAddr = destAddress;
  141. packet.IPv4Header->Length = BinaryPrimitives.ReverseEndianness((ushort)packetLength);
  142. }
  143. else
  144. {
  145. var destAddress = packet.IPv6Header->DstAddr;
  146. packet.IPv6Header->DstAddr = packet.IPv6Header->SrcAddr;
  147. packet.IPv6Header->SrcAddr = destAddress;
  148. packet.IPv6Header->Length = BinaryPrimitives.ReverseEndianness((ushort)packetLength);
  149. }
  150. // 修改udp包
  151. var destPort = packet.UdpHeader->DstPort;
  152. packet.UdpHeader->DstPort = packet.UdpHeader->SrcPort;
  153. packet.UdpHeader->SrcPort = destPort;
  154. packet.UdpHeader->Length = BinaryPrimitives.ReverseEndianness((ushort)(sizeof(UdpHeader) + responsePayload.Length));
  155. // 反转方向
  156. winDivertAddress.Impostor = true;
  157. if (winDivertAddress.Direction == WinDivertDirection.Inbound)
  158. {
  159. winDivertAddress.Direction = WinDivertDirection.Outbound;
  160. }
  161. else
  162. {
  163. winDivertAddress.Direction = WinDivertDirection.Inbound;
  164. }
  165. WinDivert.WinDivertHelperCalcChecksums(winDivertBuffer, packetLength, ref winDivertAddress, WinDivertChecksumHelperParam.All);
  166. this.logger.LogInformation($"{domain} => {IPAddress.Loopback}");
  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. }