TcpInterceptor.cs 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. public async Task InterceptAsync(CancellationToken cancellationToken)
  41. {
  42. if (this.oldServerPort == this.newServerPort)
  43. {
  44. return;
  45. }
  46. await Task.Yield();
  47. var handle = WinDivert.WinDivertOpen(this.filter, WinDivertLayer.Network, 0, WinDivertOpenFlags.None);
  48. if (handle == IntPtr.MaxValue || handle == IntPtr.Zero)
  49. {
  50. this.logger.LogError($"打开驱动失败");
  51. return;
  52. }
  53. this.logger.LogInformation($"tcp://{IPAddress.Loopback}:{BinaryPrimitives.ReverseEndianness(this.oldServerPort)} => tcp://{IPAddress.Loopback}:{BinaryPrimitives.ReverseEndianness(this.newServerPort)}");
  54. cancellationToken.Register(hwnd => WinDivert.WinDivertClose((IntPtr)hwnd!), handle);
  55. var packetLength = 0U;
  56. using var winDivertBuffer = new WinDivertBuffer();
  57. var winDivertAddress = new WinDivertAddress();
  58. while (cancellationToken.IsCancellationRequested == false)
  59. {
  60. if (WinDivert.WinDivertRecv(handle, winDivertBuffer, ref winDivertAddress, ref packetLength))
  61. {
  62. try
  63. {
  64. this.ModifyTcpPacket(winDivertBuffer, ref winDivertAddress, ref packetLength);
  65. }
  66. catch (Exception ex)
  67. {
  68. this.logger.LogWarning(ex.Message);
  69. }
  70. finally
  71. {
  72. WinDivert.WinDivertSend(handle, winDivertBuffer, packetLength, ref winDivertAddress);
  73. }
  74. }
  75. else
  76. {
  77. var exception = new Win32Exception(Marshal.GetLastWin32Error());
  78. this.logger.LogError(exception.Message);
  79. }
  80. }
  81. }
  82. /// <summary>
  83. /// 修改tcp数据端口的端口
  84. /// </summary>
  85. /// <param name="winDivertBuffer"></param>
  86. /// <param name="winDivertAddress"></param>
  87. /// <param name="packetLength"></param>
  88. unsafe private void ModifyTcpPacket(WinDivertBuffer winDivertBuffer, ref WinDivertAddress winDivertAddress, ref uint packetLength)
  89. {
  90. var packet = WinDivert.WinDivertHelperParsePacket(winDivertBuffer, packetLength);
  91. if (packet.TcpHeader->DstPort == oldServerPort)
  92. {
  93. packet.TcpHeader->DstPort = this.newServerPort;
  94. }
  95. else
  96. {
  97. packet.TcpHeader->SrcPort = oldServerPort;
  98. }
  99. winDivertAddress.Impostor = true;
  100. WinDivert.WinDivertHelperCalcChecksums(winDivertBuffer, packetLength, ref winDivertAddress, WinDivertChecksumHelperParam.All);
  101. }
  102. }
  103. }