2
0

DnsInterceptor.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. /// <exception cref="Win32Exception"></exception>
  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 == new IntPtr(unchecked((long)ulong.MaxValue)))
  60. {
  61. throw new Win32Exception();
  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) == false)
  75. {
  76. throw new Win32Exception();
  77. }
  78. try
  79. {
  80. this.ModifyDnsPacket(winDivertBuffer, ref winDivertAddress, ref packetLength);
  81. }
  82. catch (Exception ex)
  83. {
  84. this.logger.LogWarning(ex.Message);
  85. }
  86. finally
  87. {
  88. WinDivert.WinDivertSend(handle, winDivertBuffer, packetLength, ref winDivertAddress);
  89. }
  90. }
  91. }
  92. /// <summary>
  93. /// 修改DNS数据包
  94. /// </summary>
  95. /// <param name="winDivertBuffer"></param>
  96. /// <param name="winDivertAddress"></param>
  97. /// <param name="packetLength"></param>
  98. unsafe private void ModifyDnsPacket(WinDivertBuffer winDivertBuffer, ref WinDivertAddress winDivertAddress, ref uint packetLength)
  99. {
  100. var packet = WinDivert.WinDivertHelperParsePacket(winDivertBuffer, packetLength);
  101. var requestPayload = new Span<byte>(packet.PacketPayload, (int)packet.PacketPayloadLength).ToArray();
  102. if (TryParseRequest(requestPayload, out var request) == false ||
  103. request.OperationCode != OperationCode.Query ||
  104. request.Questions.Count == 0)
  105. {
  106. return;
  107. }
  108. var question = request.Questions.First();
  109. if (question.Type != RecordType.A)
  110. {
  111. return;
  112. }
  113. var domain = question.Name;
  114. if (this.fastGithubConfig.IsMatch(question.Name.ToString()) == false)
  115. {
  116. return;
  117. }
  118. // dns响应数据
  119. var response = Response.FromRequest(request);
  120. var record = new IPAddressResourceRecord(domain, IPAddress.Loopback, this.ttl);
  121. response.AnswerRecords.Add(record);
  122. var responsePayload = response.ToArray();
  123. // 修改payload和包长
  124. responsePayload.CopyTo(new Span<byte>(packet.PacketPayload, responsePayload.Length));
  125. packetLength = (uint)((int)packetLength + responsePayload.Length - requestPayload.Length);
  126. // 修改ip包
  127. if (packet.IPv4Header != null)
  128. {
  129. var destAddress = packet.IPv4Header->DstAddr;
  130. packet.IPv4Header->DstAddr = packet.IPv4Header->SrcAddr;
  131. packet.IPv4Header->SrcAddr = destAddress;
  132. packet.IPv4Header->Length = BinaryPrimitives.ReverseEndianness((ushort)packetLength);
  133. }
  134. else
  135. {
  136. var destAddress = packet.IPv6Header->DstAddr;
  137. packet.IPv6Header->DstAddr = packet.IPv6Header->SrcAddr;
  138. packet.IPv6Header->SrcAddr = destAddress;
  139. packet.IPv6Header->Length = BinaryPrimitives.ReverseEndianness((ushort)packetLength);
  140. }
  141. // 修改udp包
  142. var destPort = packet.UdpHeader->DstPort;
  143. packet.UdpHeader->DstPort = packet.UdpHeader->SrcPort;
  144. packet.UdpHeader->SrcPort = destPort;
  145. packet.UdpHeader->Length = BinaryPrimitives.ReverseEndianness((ushort)(sizeof(UdpHeader) + responsePayload.Length));
  146. winDivertAddress.Impostor = true;
  147. WinDivert.WinDivertHelperCalcChecksums(winDivertBuffer, packetLength, ref winDivertAddress, WinDivertChecksumHelperParam.All);
  148. this.logger.LogInformation($"{domain} => {IPAddress.Loopback}");
  149. }
  150. /// <summary>
  151. /// 尝试解析请求
  152. /// </summary>
  153. /// <param name="payload"></param>
  154. /// <param name="request"></param>
  155. /// <returns></returns>
  156. static bool TryParseRequest(byte[] payload, [MaybeNullWhen(false)] out Request request)
  157. {
  158. try
  159. {
  160. request = Request.FromArray(payload);
  161. return true;
  162. }
  163. catch (Exception)
  164. {
  165. request = null;
  166. return false;
  167. }
  168. }
  169. }
  170. }