TcpInterceptor.cs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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.Versioning;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using WinDivertSharp;
  10. namespace FastGithub.PacketIntercept.Tcp
  11. {
  12. /// <summary>
  13. /// tcp拦截器
  14. /// </summary>
  15. [SupportedOSPlatform("windows")]
  16. abstract class TcpInterceptor : ITcpInterceptor
  17. {
  18. private readonly string filter;
  19. private readonly ushort oldServerPort;
  20. private readonly ushort newServerPort;
  21. private readonly ILogger logger;
  22. /// <summary>
  23. /// tcp拦截器
  24. /// </summary>
  25. /// <param name="oldServerPort">修改前的服务器端口</param>
  26. /// <param name="newServerPort">修改后的服务器端口</param>
  27. /// <param name="logger"></param>
  28. public TcpInterceptor(int oldServerPort, int newServerPort, ILogger logger)
  29. {
  30. this.filter = $"loopback and (tcp.DstPort == {oldServerPort} or tcp.SrcPort == {newServerPort})";
  31. this.oldServerPort = BinaryPrimitives.ReverseEndianness((ushort)oldServerPort);
  32. this.newServerPort = BinaryPrimitives.ReverseEndianness((ushort)newServerPort);
  33. this.logger = logger;
  34. }
  35. /// <summary>
  36. /// 拦截指定端口的数据包
  37. /// </summary>
  38. /// <param name="cancellationToken"></param>
  39. /// <exception cref="Win32Exception"></exception>
  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. const int ERROR_INVALID_HANDLE = 0x6;
  51. throw new Win32Exception(ERROR_INVALID_HANDLE, "打开驱动失败");
  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) == false)
  61. {
  62. throw new Win32Exception();
  63. }
  64. try
  65. {
  66. this.ModifyTcpPacket(winDivertBuffer, ref winDivertAddress, ref packetLength);
  67. }
  68. catch (Exception ex)
  69. {
  70. this.logger.LogWarning(ex.Message);
  71. }
  72. finally
  73. {
  74. WinDivert.WinDivertSend(handle, winDivertBuffer, packetLength, ref winDivertAddress);
  75. }
  76. }
  77. }
  78. /// <summary>
  79. /// 修改tcp数据端口的端口
  80. /// </summary>
  81. /// <param name="winDivertBuffer"></param>
  82. /// <param name="winDivertAddress"></param>
  83. /// <param name="packetLength"></param>
  84. unsafe private void ModifyTcpPacket(WinDivertBuffer winDivertBuffer, ref WinDivertAddress winDivertAddress, ref uint packetLength)
  85. {
  86. var packet = WinDivert.WinDivertHelperParsePacket(winDivertBuffer, packetLength);
  87. if (packet.TcpHeader->DstPort == oldServerPort)
  88. {
  89. packet.TcpHeader->DstPort = this.newServerPort;
  90. }
  91. else
  92. {
  93. packet.TcpHeader->SrcPort = oldServerPort;
  94. }
  95. winDivertAddress.Impostor = true;
  96. WinDivert.WinDivertHelperCalcChecksums(winDivertBuffer, packetLength, ref winDivertAddress, WinDivertChecksumHelperParam.All);
  97. }
  98. }
  99. }