TcpInterceptor.cs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using Microsoft.Extensions.Logging;
  2. using System;
  3. using System.Buffers.Binary;
  4. using System.ComponentModel;
  5. using System.Net;
  6. using System.Runtime.InteropServices;
  7. using System.Runtime.Versioning;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using WinDivertSharp;
  11. namespace FastGithub.PacketIntercept.Tcp
  12. {
  13. /// <summary>
  14. /// tcp拦截器
  15. /// </summary>
  16. [SupportedOSPlatform("windows")]
  17. abstract class TcpInterceptor : ITcpInterceptor
  18. {
  19. private readonly string filter;
  20. private readonly ushort oldServerPort;
  21. private readonly ushort newServerPort;
  22. private readonly ILogger logger;
  23. /// <summary>
  24. /// tcp拦截器
  25. /// </summary>
  26. /// <param name="oldServerPort">修改前的服务器端口</param>
  27. /// <param name="newServerPort">修改后的服务器端口</param>
  28. /// <param name="logger"></param>
  29. public TcpInterceptor(int oldServerPort, int newServerPort, ILogger logger)
  30. {
  31. this.filter = $"loopback and (tcp.DstPort == {oldServerPort} or tcp.SrcPort == {newServerPort})";
  32. this.oldServerPort = BinaryPrimitives.ReverseEndianness((ushort)oldServerPort);
  33. this.newServerPort = BinaryPrimitives.ReverseEndianness((ushort)newServerPort);
  34. this.logger = logger;
  35. }
  36. /// <summary>
  37. /// 拦截指定端口的数据包
  38. /// </summary>
  39. /// <param name="cancellationToken"></param>
  40. /// <exception cref="Win32Exception"></exception>
  41. public async Task InterceptAsync(CancellationToken cancellationToken)
  42. {
  43. if (this.oldServerPort == this.newServerPort)
  44. {
  45. return;
  46. }
  47. await Task.Yield();
  48. var handle = WinDivert.WinDivertOpen(this.filter, WinDivertLayer.Network, 0, WinDivertOpenFlags.None);
  49. if (handle == IntPtr.MaxValue || handle == IntPtr.Zero)
  50. {
  51. const int ERROR_INVALID_HANDLE = 0x6;
  52. throw new Win32Exception(ERROR_INVALID_HANDLE, "打开驱动失败");
  53. }
  54. this.logger.LogInformation($"tcp://{IPAddress.Loopback}:{BinaryPrimitives.ReverseEndianness(this.oldServerPort)} => tcp://{IPAddress.Loopback}:{BinaryPrimitives.ReverseEndianness(this.newServerPort)}");
  55. cancellationToken.Register(hwnd => WinDivert.WinDivertClose((IntPtr)hwnd!), handle);
  56. var packetLength = 0U;
  57. using var winDivertBuffer = new WinDivertBuffer();
  58. var winDivertAddress = new WinDivertAddress();
  59. while (cancellationToken.IsCancellationRequested == false)
  60. {
  61. if (WinDivert.WinDivertRecv(handle, winDivertBuffer, ref winDivertAddress, ref packetLength))
  62. {
  63. try
  64. {
  65. this.ModifyTcpPacket(winDivertBuffer, ref winDivertAddress, ref packetLength);
  66. }
  67. catch (Exception ex)
  68. {
  69. this.logger.LogWarning(ex.Message);
  70. }
  71. finally
  72. {
  73. WinDivert.WinDivertSend(handle, winDivertBuffer, packetLength, ref winDivertAddress);
  74. }
  75. }
  76. else
  77. {
  78. var errorCode = Marshal.GetLastWin32Error();
  79. throw new Win32Exception(errorCode);
  80. }
  81. }
  82. }
  83. /// <summary>
  84. /// 修改tcp数据端口的端口
  85. /// </summary>
  86. /// <param name="winDivertBuffer"></param>
  87. /// <param name="winDivertAddress"></param>
  88. /// <param name="packetLength"></param>
  89. unsafe private void ModifyTcpPacket(WinDivertBuffer winDivertBuffer, ref WinDivertAddress winDivertAddress, ref uint packetLength)
  90. {
  91. var packet = WinDivert.WinDivertHelperParsePacket(winDivertBuffer, packetLength);
  92. if (packet.TcpHeader->DstPort == oldServerPort)
  93. {
  94. packet.TcpHeader->DstPort = this.newServerPort;
  95. }
  96. else
  97. {
  98. packet.TcpHeader->SrcPort = oldServerPort;
  99. }
  100. winDivertAddress.Impostor = true;
  101. WinDivert.WinDivertHelperCalcChecksums(winDivertBuffer, packetLength, ref winDivertAddress, WinDivertChecksumHelperParam.All);
  102. }
  103. }
  104. }