Skip to content

#1754 Add Modbus Support #1823

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 30 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
a36e594
Add ModbusLayer first implementation with header parsing only
yahyayozo May 18, 2025
88f69d4
fix static_assert
yahyayozo May 18, 2025
c257494
Merge branch 'dev' into feature/modbus
yahyayozo May 18, 2025
348afc6
Fix formatting in ModbusLayer header file
yahyayozo May 21, 2025
1f65c24
Add setter methods for MODBUS header fields in ModbusLayer
yahyayozo May 21, 2025
4159c6c
Merge branch 'dev' into feature/modbus
yahyayozo May 21, 2025
58c18ec
Refactor ModbusLayer class documentation and fix syntax error
yahyayozo May 23, 2025
d50db3b
Merge branch 'feature/modbus' of https://github.com/yahyayozo/PcapPlu…
yahyayozo May 23, 2025
cfcbc69
Fix endianess handling in ModbusLayer getters and setters
yahyayozo May 23, 2025
28dd176
Add const qualifier to ModbusLayer getter methods
yahyayozo May 23, 2025
34d65a2
Add constructors to ModbusLayer for initializing from user inputs
yahyayozo May 23, 2025
74ab79d
Add Modbus protocol constant to ProtocolType
yahyayozo May 24, 2025
166c15c
Add const qualifier to ModbusLayer getter methods in .h file
yahyayozo May 28, 2025
3624286
Add ModbusLayer and corresponding tests to Packet++Test
yahyayozo May 29, 2025
bcd14b5
Fix length assignment in ModbusLayer constructor to use htobe16
yahyayozo May 31, 2025
9f4ebbd
Refactor ModbusLayerParsingTest to create ModbusLayer from a dat file…
yahyayozo Jun 4, 2025
4ceb41d
Fix formatting in ModbusLayer constructor for improved readability
yahyayozo Jun 15, 2025
adb3f51
Remove redundant ModbusLayerParsingTest case from ModbusTests.cpp
yahyayozo Jun 15, 2025
839aa49
Remove ModbusLayerParsingTest from test definitions and main execution
yahyayozo Jun 15, 2025
dc04c0c
Fix newline at end of file in ModbusLayerCreationTest and TestDefinit…
yahyayozo Jun 15, 2025
f4f5291
Add ModbusLayer parsing test and utility function for port validation
yahyayozo Jun 16, 2025
24c0924
Merge branch 'dev' into feature/modbus
yahyayozo Jun 16, 2025
32da5e5
Add missing includes for iostream and iomanip in ModbusLayer.cpp
yahyayozo Jun 17, 2025
da52bf7
Refactor ModbusLayerCreationTest to include additional assertions for…
yahyayozo Jun 17, 2025
c8bd099
Merge branch 'feature/modbus' of https://github.com/yahyayozo/PcapPlu…
yahyayozo Jun 17, 2025
b96671c
Merge branch 'dev' into feature/modbus
yahyayozo Jul 21, 2025
5dd18fb
Merge branch 'dev' into feature/modbus
yahyayozo Jul 30, 2025
4b38a65
Refactor Modbus header structure and update related methods for consi…
yahyayozo Jul 30, 2025
65b37f6
Merge branch 'feature/modbus' of https://github.com/yahyayozo/PcapPlu…
yahyayozo Jul 30, 2025
32211b8
Fix ModbusLayer::toString method declaration for consistency
yahyayozo Jul 31, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Packet++/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ add_library(
src/Layer.cpp
src/LdapLayer.cpp
src/LLCLayer.cpp
src/ModbusLayer.cpp
src/MplsLayer.cpp
src/NdpLayer.cpp
src/NflogLayer.cpp
Expand Down
119 changes: 119 additions & 0 deletions Packet++/header/ModbusLayer.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
#pragma once

#include "Layer.h"

/// @file
/// This file contains classes for parsing, creating and editing Modbus packets.

/// @namespace pcpp
/// @brief The main namespace for the PcapPlusPlus lib
namespace pcpp
{

#pragma pack(push, 1)
/// @struct modbus_header
/// MODBUS Application Protocol header
struct modbus_header
{
/// For synchronization between messages of server and client
uint16_t transactionId;
/// 0 for Modbus/TCP
uint16_t protocolId;
/// Number of remaining bytes in this frame starting from the unit id
uint16_t length;
/// Unit identifier
uint8_t unitId;
/// Function code
uint8_t functionCode;
};
#pragma pack(pop)
static_assert(sizeof(modbus_header) == 8, "modbus_header size is not 8 bytes");

/// @class ModbusLayer
/// Represents the MODBUS Application Protocol layer
class ModbusLayer : public Layer
{
public:
/// A constructor that creates the layer from an existing packet raw data
/// @param[in] data A pointer to the raw data
/// @param[in] dataLen Size of the data in bytes
/// @param[in] prevLayer A pointer to the previous layer
/// @param[in] packet A pointer to the Packet instance where layer will be stored in
ModbusLayer(uint8_t* data, size_t dataLen, Layer* prevLayer, Packet* packet)
: Layer(data, dataLen, prevLayer, packet, Modbus)
{}

/// A constructor that creates the layer from user inputs
/// @param[in] transactionId Transaction ID
/// @param[in] unitId Unit ID
/// @param[in] functionCode Function code
ModbusLayer(uint16_t transactionId, uint8_t unitId, uint8_t functionCode);

/// @brief Check if a port is a valid MODBUS port
/// @param port
/// @return true if the port is valid, false otherwise
static bool isModbusPort(uint16_t port)
{
return port == 502;
}

/// @return A pointer to the MODBUS header
modbus_header* getModbusHeader() const;

/// @return MODBUS message type
uint16_t getTransactionId() const;

/// @return MODBUS protocol id
uint16_t getProtocolId() const;

/// @return MODBUS remaining bytes in frame starting from the unit id
/// @note This is the length of the MODBUS payload + unit_id, not the entire packet
uint16_t getLength() const;

/// @return MODBUS unit id
uint8_t getUnitId() const;

/// @return MODBUS function code
uint8_t getFunctionCode() const;

/// @brief set the MODBUS transaction id
/// @param transactionId transaction id
void setTransactionId(uint16_t transactionId);

/// @brief set the MODBUS header unit id
/// @param unitId unit id
void setUnitId(uint8_t unitId);

/// @brief set the MODBUS header function code
/// @param functionCode function code
void setFunctionCode(uint8_t functionCode);

// Overridden methods

/// Does nothing for this layer (ModbusLayer is always last)
void parseNextLayer() override
{}

/// @brief Get the length of the MODBUS header
/// @return Length of the MODBUS header in bytes
size_t getHeaderLen() const override
{
return sizeof(modbus_header);
}

/// Each layer can compute field values automatically using this method. This is an abstract method
void computeCalculateFields() override
{}

/// @return A string representation of the layer most important data (should look like the layer description in
/// Wireshark)
std::string toString() const override;

/// @return The OSI Model layer this protocol belongs to
OsiModelLayer getOsiModelLayer() const override
{
return OsiModelApplicationLayer;
}
};

} // namespace pcpp
3 changes: 3 additions & 0 deletions Packet++/header/ProtocolType.h
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,9 @@ namespace pcpp
/// Cisco HDLC protocol
const ProtocolType CiscoHDLC = 58;

/// Modbus protocol
const ProtocolType Modbus = 59;

/// An enum representing OSI model layers
enum OsiModelLayer
{
Expand Down
77 changes: 77 additions & 0 deletions Packet++/src/ModbusLayer.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
#include "ModbusLayer.h"
#include "EndianPortable.h"
#include <iostream>
#include <iomanip>
#include <cstring>

namespace pcpp
{
ModbusLayer::ModbusLayer(uint16_t transactionId, uint8_t unitId, uint8_t functionCode)
{
const size_t headerLen = sizeof(modbus_header);
m_DataLen = headerLen;
m_Data = new uint8_t[headerLen];
memset(m_Data, 0, headerLen);

// Initialize the header fields to default values
modbus_header* header = getModbusHeader();
header->transactionId = htobe16(transactionId);
header->protocolId = 0; // 0 for Modbus/TCP
header->length = htobe16(2); // minimum length of the MODBUS payload + unit_id
header->unitId = unitId;
header->functionCode = functionCode;
}

modbus_header* ModbusLayer::getModbusHeader() const
{
return (modbus_header*)m_Data;
}

uint16_t ModbusLayer::getTransactionId() const
{
return be16toh(getModbusHeader()->transactionId);
}

uint16_t ModbusLayer::getProtocolId() const
{
return be16toh(getModbusHeader()->protocolId);
}

uint16_t ModbusLayer::getLength() const
{
return be16toh(getModbusHeader()->length);
}

uint8_t ModbusLayer::getUnitId() const
{
return getModbusHeader()->unitId;
}

uint8_t ModbusLayer::getFunctionCode() const
{
return getModbusHeader()->functionCode;
}

void ModbusLayer::setTransactionId(uint16_t transactionId)
{
getModbusHeader()->transactionId = htobe16(transactionId);
}

void ModbusLayer::setUnitId(uint8_t unitId)
{
getModbusHeader()->unitId = unitId;
}

void ModbusLayer::setFunctionCode(uint8_t functionCode)
{
getModbusHeader()->functionCode = functionCode;
}

std::string ModbusLayer::toString() const
{
return "Modbus Layer, Transaction ID: " + std::to_string(getTransactionId()) +
", Protocol ID: " + std::to_string(getProtocolId()) + ", Length: " + std::to_string(getLength()) +
", Unit ID: " + std::to_string(getUnitId()) + ", Function Code: " + std::to_string(getFunctionCode());
}

} // namespace pcpp
5 changes: 5 additions & 0 deletions Packet++/src/TcpLayer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#include "SmtpLayer.h"
#include "LdapLayer.h"
#include "GtpLayer.h"
#include "ModbusLayer.h"
#include "PacketUtils.h"
#include "Logger.h"
#include "DeprecationUtils.h"
Expand Down Expand Up @@ -456,6 +457,10 @@ namespace pcpp
{
constructNextLayer<GtpV2Layer>(payload, payloadLen, m_Packet);
}
else if (ModbusLayer::isModbusPort(portDst))
{
constructNextLayer<ModbusLayer>(payload, payloadLen, m_Packet);
}
else
{
constructNextLayer<PayloadLayer>(payload, payloadLen, m_Packet);
Expand Down
1 change: 1 addition & 0 deletions Tests/Packet++Test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ add_executable(
Tests/IPv6Tests.cpp
Tests/LdapTests.cpp
Tests/LLCTests.cpp
Tests/ModbusTests.cpp
Tests/NflogTests.cpp
Tests/NtpTests.cpp
Tests/PacketTests.cpp
Expand Down
1 change: 1 addition & 0 deletions Tests/Packet++Test/PacketExamples/ModbusRequest.dat
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0002b3ce705100207800620d08004500003085a14000800660eb0a0000390a0000030a1201f66197f1e370f1ad6f5018fa9c18f500000000000000020a11
4 changes: 4 additions & 0 deletions Tests/Packet++Test/TestDefinition.h
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,10 @@ PTF_TEST_CASE(CiscoHdlcParsingTest);
PTF_TEST_CASE(CiscoHdlcLayerCreationTest);
PTF_TEST_CASE(CiscoHdlcLayerEditTest);

// Implemented in ModbusTests.cpp
PTF_TEST_CASE(ModbusLayerCreationTest);
PTF_TEST_CASE(ModbusLayerParsingTest);

// Implemented in X509Tests.cpp
PTF_TEST_CASE(X509ParsingTest);
PTF_TEST_CASE(X509VariantsParsingTest);
Expand Down
53 changes: 53 additions & 0 deletions Tests/Packet++Test/Tests/ModbusTests.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#include "../TestDefinition.h"
#include "../Utils/TestUtils.h"
#include "Packet.h"
#include "ModbusLayer.h"
#include "EndianPortable.h"
#include "SystemUtils.h"

PTF_TEST_CASE(ModbusLayerCreationTest)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The best way to test layer creation is to compare it to a real packet. You can load ModbusRequest.dat, extract the modbus layer and compare it to the created packet in this test

{
pcpp::ModbusLayer modbusLayer(12345, 1, 3);

PTF_ASSERT_EQUAL(modbusLayer.getTransactionId(), 12345);
PTF_ASSERT_EQUAL(modbusLayer.getProtocolId(), 0);
PTF_ASSERT_EQUAL(modbusLayer.getLength(), 2); // minimum length of the MODBUS payload + unit_id
PTF_ASSERT_EQUAL(modbusLayer.getUnitId(), 1);
PTF_ASSERT_EQUAL(modbusLayer.getFunctionCode(), 3);
PTF_ASSERT_EQUAL(modbusLayer.getHeaderLen(), sizeof(pcpp::modbus_header));

PTF_ASSERT_EQUAL(modbusLayer.getOsiModelLayer(), pcpp::OsiModelApplicationLayer);

modbusLayer.setTransactionId(54321);
PTF_ASSERT_EQUAL(modbusLayer.getTransactionId(), 54321);
modbusLayer.setUnitId(2);
PTF_ASSERT_EQUAL(modbusLayer.getUnitId(), 2);
modbusLayer.setFunctionCode(6);
PTF_ASSERT_EQUAL(modbusLayer.getFunctionCode(), 6);

// just to pass the codecov
modbusLayer.computeCalculateFields();

} // ModbusLayerCreationTest

PTF_TEST_CASE(ModbusLayerParsingTest)
{
timeval time;
gettimeofday(&time, nullptr);

READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/ModbusRequest.dat");

pcpp::Packet packet(&rawPacket1);
PTF_ASSERT_TRUE(packet.isPacketOfType(pcpp::Modbus));

pcpp::ModbusLayer* modbusLayer = packet.getLayerOfType<pcpp::ModbusLayer>();
PTF_ASSERT_NOT_NULL(modbusLayer);
PTF_ASSERT_EQUAL(modbusLayer->getTransactionId(), 0);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you get a packet where transaction ID is not 0?

PTF_ASSERT_EQUAL(modbusLayer->getProtocolId(), 0);
PTF_ASSERT_EQUAL(modbusLayer->getLength(), 2);
PTF_ASSERT_EQUAL(modbusLayer->getUnitId(), 10);
PTF_ASSERT_EQUAL(modbusLayer->getFunctionCode(), 17);

PTF_ASSERT_EQUAL(modbusLayer->toString(),
"Modbus Layer, Transaction ID: 12345, Protocol ID: 0, Length: 2, Unit ID: 1, Function Code: 3");
} // ModbusLayerParsingTest
3 changes: 3 additions & 0 deletions Tests/Packet++Test/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,9 @@ int main(int argc, char* argv[])
PTF_RUN_TEST(CiscoHdlcLayerCreationTest, "chdlc");
PTF_RUN_TEST(CiscoHdlcLayerEditTest, "chdlc");

PTF_RUN_TEST(ModbusLayerCreationTest, "modbus");
PTF_RUN_TEST(ModbusLayerParsingTest, "modbus");

PTF_RUN_TEST(X509ParsingTest, "x509");
PTF_RUN_TEST(X509VariantsParsingTest, "x509");
PTF_RUN_TEST(X509InvalidDataTest, "x509");
Expand Down
Loading