1

I am trying to reverse engineer my device and its software communication protocol. The device is connected via COM port, so my idea is to create a pair of connected virtual COM ports, connect its software to one of them and then resend all the data from the second virtual COM port to the device and vice versa while logging everything that goes by. That is, some sort of man-in-the-middle.

But, even though I can monitor to some data from both the device and the software, they do not seem to recognize each other correctly. They do, however, if I try to connect them directly to one another. I suppose the problem is somewhere in the resending part.

My code currently looks like this:

public class ComMitm : IDisposable
{
    public SerialPort VirtualPort { get; }
    public SerialPort DevicePort { get; }

    public ICollection<string> Log { get; } = new List<string>();

    public ComMitm(string virtualPort, string devicePort)
    {
        VirtualPort = new SerialPort(virtualPort, 9600, Parity.None, 8, StopBits.One);
        DevicePort = new SerialPort(devicePort, 9600, Parity.None, 8, StopBits.One);

        VirtualPort.DataReceived += (sender, args) => { ResendData(VirtualPort, DevicePort); };
        DevicePort.DataReceived += (sender, args) => { ResendData(DevicePort, VirtualPort); };
    }

    public void StartListening()
    {
        VirtualPort.Open();
        DevicePort.Open();
    }

    private void ResendData(SerialPort fromPort, SerialPort toPort)
    {
        var data = fromPort.ReadExisting();
        toPort.Write(data);
        string logText = $"{fromPort.PortName} -> {toPort.PortName}: {data}"; 
        Console.WriteLine(logText);
        Log.Add(logText);
    }

    public void Dispose()
    {
        VirtualPort?.Dispose();
        DevicePort?.Dispose();
    }
}

I call it like this:

using (var mitm = new ComMitm("COM1", "COM8"))
{
  mitm.StartListening();
  do
  {
    Thread.Sleep(1000);
  } while (true);
}

(The calling code is for debug purpose only, so nevermind the endless loop).

Thank you in advance!

bashis
  • 1,200
  • 1
  • 16
  • 35

0 Answers0