2
0

TcpInterceptor.cs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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 const int ERROR_INVALID_HANDLE = 0x6;
  20. private readonly string filter;
  21. private readonly ushort oldServerPort;
  22. private readonly ushort newServerPort;
  23. private readonly ILogger logger;
  24. /// <summary>
  25. /// tcp拦截器
  26. /// </summary>
  27. /// <param name="oldServerPort">修改前的服务器端口</param>
  28. /// <param name="newServerPort">修改后的服务器端口</param>
  29. /// <param name="logger"></param>
  30. public TcpInterceptor(int oldServerPort, int newServerPort, ILogger logger)
  31. {
  32. this.filter = $"loopback and (tcp.DstPort == {oldServerPort} or tcp.SrcPort == {newServerPort})";
  33. this.oldServerPort = BinaryPrimitives.ReverseEndianness((ushort)oldServerPort);
  34. this.newServerPort = BinaryPrimitives.ReverseEndianness((ushort)newServerPort);
  35. this.logger = logger;
  36. }
  37. /// <summary>
  38. /// 拦截指定端口的数据包
  39. /// </summary>
  40. /// <param name="cancellationToken"></param>
  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. this.logger.LogError($"打开驱动失败");
  52. return;
  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. this.logger.LogError(new Win32Exception(errorCode).Message);
  80. if (errorCode == ERROR_INVALID_HANDLE)
  81. {
  82. break;
  83. }
  84. }
  85. }
  86. }
  87. /// <summary>
  88. /// 修改tcp数据端口的端口
  89. /// </summary>
  90. /// <param name="winDivertBuffer"></param>
  91. /// <param name="winDivertAddress"></param>
  92. /// <param name="packetLength"></param>
  93. unsafe private void ModifyTcpPacket(WinDivertBuffer winDivertBuffer, ref WinDivertAddress winDivertAddress, ref uint packetLength)
  94. {
  95. var packet = WinDivert.WinDivertHelperParsePacket(winDivertBuffer, packetLength);
  96. if (packet.TcpHeader->DstPort == oldServerPort)
  97. {
  98. packet.TcpHeader->DstPort = this.newServerPort;
  99. }
  100. else
  101. {
  102. packet.TcpHeader->SrcPort = oldServerPort;
  103. }
  104. winDivertAddress.Impostor = true;
  105. WinDivert.WinDivertHelperCalcChecksums(winDivertBuffer, packetLength, ref winDivertAddress, WinDivertChecksumHelperParam.All);
  106. }
  107. }
  108. }