DnsInterceptor.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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.Diagnostics.CodeAnalysis;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Runtime.InteropServices;
  12. using System.Runtime.Versioning;
  13. using System.Threading;
  14. using WinDivertSharp;
  15. namespace FastGithub.Dns
  16. {
  17. /// <summary>
  18. /// dns拦截器
  19. /// </summary>
  20. [SupportedOSPlatform("windows")]
  21. sealed class DnsInterceptor
  22. {
  23. private const string DNS_FILTER = "udp.DstPort == 53";
  24. private readonly FastGithubConfig fastGithubConfig;
  25. private readonly ILogger<DnsInterceptor> logger;
  26. private readonly TimeSpan ttl = TimeSpan.FromMinutes(2d);
  27. /// <summary>
  28. /// 刷新DNS缓存
  29. /// </summary>
  30. [DllImport("dnsapi.dll", EntryPoint = "DnsFlushResolverCache", SetLastError = true)]
  31. private static extern void DnsFlushResolverCache();
  32. /// <summary>
  33. /// dns拦截器
  34. /// </summary>
  35. /// <param name="fastGithubConfig"></param>
  36. /// <param name="logger"></param>
  37. /// <param name="options"></param>
  38. public DnsInterceptor(
  39. FastGithubConfig fastGithubConfig,
  40. ILogger<DnsInterceptor> logger,
  41. IOptionsMonitor<FastGithubOptions> options)
  42. {
  43. this.fastGithubConfig = fastGithubConfig;
  44. this.logger = logger;
  45. options.OnChange(_ => DnsFlushResolverCache());
  46. }
  47. /// <summary>
  48. /// DNS拦截
  49. /// </summary>
  50. /// <param name="cancellationToken"></param>
  51. public void Intercept(CancellationToken cancellationToken)
  52. {
  53. var handle = WinDivert.WinDivertOpen(DNS_FILTER, WinDivertLayer.Network, 0, WinDivertOpenFlags.None);
  54. if (handle == IntPtr.Zero)
  55. {
  56. return;
  57. }
  58. cancellationToken.Register(hwnd =>
  59. {
  60. WinDivert.WinDivertClose((IntPtr)hwnd!);
  61. DnsFlushResolverCache();
  62. }, handle);
  63. var packetLength = 0U;
  64. using var winDivertBuffer = new WinDivertBuffer();
  65. var winDivertAddress = new WinDivertAddress();
  66. DnsFlushResolverCache();
  67. while (cancellationToken.IsCancellationRequested == false)
  68. {
  69. if (WinDivert.WinDivertRecv(handle, winDivertBuffer, ref winDivertAddress, ref packetLength))
  70. {
  71. try
  72. {
  73. this.ModifyDnsPacket(winDivertBuffer, ref winDivertAddress, ref packetLength);
  74. }
  75. catch (Exception ex)
  76. {
  77. this.logger.LogWarning(ex.Message);
  78. }
  79. finally
  80. {
  81. WinDivert.WinDivertSend(handle, winDivertBuffer, packetLength, ref winDivertAddress);
  82. }
  83. }
  84. }
  85. }
  86. /// <summary>
  87. /// 修改DNS数据包
  88. /// </summary>
  89. /// <param name="winDivertBuffer"></param>
  90. /// <param name="winDivertAddress"></param>
  91. /// <param name="packetLength"></param>
  92. unsafe private void ModifyDnsPacket(WinDivertBuffer winDivertBuffer, ref WinDivertAddress winDivertAddress, ref uint packetLength)
  93. {
  94. var packet = WinDivert.WinDivertHelperParsePacket(winDivertBuffer, packetLength);
  95. var requestPayload = new Span<byte>(packet.PacketPayload, (int)packet.PacketPayloadLength).ToArray();
  96. if (TryParseRequest(requestPayload, out var request) == false ||
  97. request.OperationCode != OperationCode.Query ||
  98. request.Questions.Count == 0)
  99. {
  100. return;
  101. }
  102. var question = request.Questions.First();
  103. if (question.Type != RecordType.A)
  104. {
  105. return;
  106. }
  107. var domain = question.Name;
  108. if (this.fastGithubConfig.IsMatch(question.Name.ToString()) == false)
  109. {
  110. return;
  111. }
  112. // dns响应数据
  113. var response = Response.FromRequest(request);
  114. var record = new IPAddressResourceRecord(domain, IPAddress.Loopback, this.ttl);
  115. response.AnswerRecords.Add(record);
  116. var responsePayload = response.ToArray();
  117. // 修改payload和包长
  118. responsePayload.CopyTo(new Span<byte>(packet.PacketPayload, responsePayload.Length));
  119. packetLength = (uint)((int)packetLength + responsePayload.Length - requestPayload.Length);
  120. // 修改ip包
  121. if (packet.IPv4Header != null)
  122. {
  123. var destAddress = packet.IPv4Header->DstAddr;
  124. packet.IPv4Header->DstAddr = packet.IPv4Header->SrcAddr;
  125. packet.IPv4Header->SrcAddr = destAddress;
  126. packet.IPv4Header->Length = BinaryPrimitives.ReverseEndianness((ushort)packetLength);
  127. }
  128. else
  129. {
  130. var destAddress = packet.IPv6Header->DstAddr;
  131. packet.IPv6Header->DstAddr = packet.IPv6Header->SrcAddr;
  132. packet.IPv6Header->SrcAddr = destAddress;
  133. packet.IPv6Header->Length = BinaryPrimitives.ReverseEndianness((ushort)packetLength);
  134. }
  135. // 修改udp包
  136. var destPort = packet.UdpHeader->DstPort;
  137. packet.UdpHeader->DstPort = packet.UdpHeader->SrcPort;
  138. packet.UdpHeader->SrcPort = destPort;
  139. packet.UdpHeader->Length = BinaryPrimitives.ReverseEndianness((ushort)(sizeof(UdpHeader) + responsePayload.Length));
  140. // 反转方向
  141. winDivertAddress.Impostor = true;
  142. if (winDivertAddress.Direction == WinDivertDirection.Inbound)
  143. {
  144. winDivertAddress.Direction = WinDivertDirection.Outbound;
  145. }
  146. else
  147. {
  148. winDivertAddress.Direction = WinDivertDirection.Inbound;
  149. }
  150. WinDivert.WinDivertHelperCalcChecksums(winDivertBuffer, packetLength, ref winDivertAddress, WinDivertChecksumHelperParam.All);
  151. this.logger.LogInformation($"已拦截dns查询{domain}并伪造解析结果为{IPAddress.Loopback}");
  152. }
  153. /// <summary>
  154. /// 尝试解析请求
  155. /// </summary>
  156. /// <param name="payload"></param>
  157. /// <param name="request"></param>
  158. /// <returns></returns>
  159. static bool TryParseRequest(byte[] payload, [MaybeNullWhen(false)] out Request request)
  160. {
  161. try
  162. {
  163. request = Request.FromArray(payload);
  164. return true;
  165. }
  166. catch (Exception)
  167. {
  168. request = null;
  169. return false;
  170. }
  171. }
  172. }
  173. }