DnsInterceptor.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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(10d);
  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. /// <exception cref="Win32Exception"></exception>
  53. /// <returns></returns>
  54. public async Task InterceptAsync(CancellationToken cancellationToken)
  55. {
  56. await Task.Yield();
  57. var handle = WinDivert.WinDivertOpen(DNS_FILTER, WinDivertLayer.Network, 0, WinDivertOpenFlags.None);
  58. if (handle == new IntPtr(unchecked((long)ulong.MaxValue)))
  59. {
  60. throw new Win32Exception();
  61. }
  62. cancellationToken.Register(hwnd =>
  63. {
  64. WinDivert.WinDivertClose((IntPtr)hwnd!);
  65. DnsFlushResolverCache();
  66. }, handle);
  67. var packetLength = 0U;
  68. using var winDivertBuffer = new WinDivertBuffer();
  69. var winDivertAddress = new WinDivertAddress();
  70. DnsFlushResolverCache();
  71. while (cancellationToken.IsCancellationRequested == false)
  72. {
  73. if (WinDivert.WinDivertRecv(handle, winDivertBuffer, ref winDivertAddress, ref packetLength) == false)
  74. {
  75. throw new Win32Exception();
  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. }
  91. /// <summary>
  92. /// 修改DNS数据包
  93. /// </summary>
  94. /// <param name="winDivertBuffer"></param>
  95. /// <param name="winDivertAddress"></param>
  96. /// <param name="packetLength"></param>
  97. unsafe private void ModifyDnsPacket(WinDivertBuffer winDivertBuffer, ref WinDivertAddress winDivertAddress, ref uint packetLength)
  98. {
  99. var packet = WinDivert.WinDivertHelperParsePacket(winDivertBuffer, packetLength);
  100. var requestPayload = new Span<byte>(packet.PacketPayload, (int)packet.PacketPayloadLength).ToArray();
  101. if (TryParseRequest(requestPayload, out var request) == false ||
  102. request.OperationCode != OperationCode.Query ||
  103. request.Questions.Count == 0)
  104. {
  105. return;
  106. }
  107. var question = request.Questions.First();
  108. if (question.Type != RecordType.A)
  109. {
  110. return;
  111. }
  112. var domain = question.Name;
  113. if (this.fastGithubConfig.IsMatch(question.Name.ToString()) == false)
  114. {
  115. return;
  116. }
  117. // dns响应数据
  118. var response = Response.FromRequest(request);
  119. var record = new IPAddressResourceRecord(domain, IPAddress.Loopback, this.ttl);
  120. response.AnswerRecords.Add(record);
  121. var responsePayload = response.ToArray();
  122. // 修改payload和包长
  123. responsePayload.CopyTo(new Span<byte>(packet.PacketPayload, responsePayload.Length));
  124. packetLength = (uint)((int)packetLength + responsePayload.Length - requestPayload.Length);
  125. // 修改ip包
  126. if (packet.IPv4Header != null)
  127. {
  128. var destAddress = packet.IPv4Header->DstAddr;
  129. packet.IPv4Header->DstAddr = packet.IPv4Header->SrcAddr;
  130. packet.IPv4Header->SrcAddr = destAddress;
  131. packet.IPv4Header->Length = (ushort)packetLength;
  132. }
  133. else
  134. {
  135. var destAddress = packet.IPv6Header->DstAddr;
  136. packet.IPv6Header->DstAddr = packet.IPv6Header->SrcAddr;
  137. packet.IPv6Header->SrcAddr = destAddress;
  138. packet.IPv6Header->Length = (ushort)packetLength;
  139. }
  140. // 修改udp包
  141. var destPort = packet.UdpHeader->DstPort;
  142. packet.UdpHeader->DstPort = packet.UdpHeader->SrcPort;
  143. packet.UdpHeader->SrcPort = destPort;
  144. packet.UdpHeader->Length = (ushort)(sizeof(UdpHeader) + responsePayload.Length);
  145. winDivertAddress.Impostor = true;
  146. WinDivert.WinDivertHelperCalcChecksums(winDivertBuffer, packetLength, ref winDivertAddress, WinDivertChecksumHelperParam.All);
  147. }
  148. /// <summary>
  149. /// 尝试解析请求
  150. /// </summary>
  151. /// <param name="payload"></param>
  152. /// <param name="request"></param>
  153. /// <returns></returns>
  154. static bool TryParseRequest(byte[] payload, [MaybeNullWhen(false)] out Request request)
  155. {
  156. try
  157. {
  158. request = Request.FromArray(payload);
  159. return true;
  160. }
  161. catch (Exception)
  162. {
  163. request = null;
  164. return false;
  165. }
  166. }
  167. }
  168. }