

Today, let’s talk about Modbus. First, let’s look at the main content for today:
01 Terminology Interpretation
02 Background
03 Protocol Principles
04 Transmission Methods
05 Differences Between Modbus RTU and Modbus ASCII
06 Modbus TCP and Its Considerations
07 Function Code Functions
08 Modbus Protocol Security Analysis
Checksum: The checksum is usually the last digit of a group of numbers, derived from the previous numbers through some operation, used to verify the correctness of that group of data. When data is input to a computer or other devices, input errors can easily occur, so coding experts have invented various checksum error detection methods and established checksums based on these methods. Common checksums include: Sum, XOR, LRC, CRC…
Discrete Input: Mainly used to read the state of a single bit, such as the status of an I/O;
Coil: Switch output signal, mainly used to write a single bit of data, forming a paired operation with discrete inputs;
Input Register: Mainly used to read 16-bit data, which is two bytes;
Holding Register: Mainly used to write 16-bit data;
PLC: A Programmable Logic Controller is a type of programmable storage device used for storing programs and executing logical operations, sequential control, timing, counting, and arithmetic operations, and it controls various types of machinery or production processes through digital or analog input/output.
Serial Communication: As computer systems and microcomputer networks have developed, communication functions have become increasingly important. Here, communication refers to the exchange of information between computers and the outside world. Thus, communication includes both the exchange of information between computers and external devices, as well as between computers themselves. Serial communication transmits information one bit at a time over a single transmission line, requiring fewer transmission lines, and can utilize existing telephone networks for information transmission, making it particularly suitable for long-distance transmission. For devices that are not far from the computer, such as human-machine interface devices and serially stored external devices like terminals, printers, logic analyzers, and disks, serial data exchange is also common. In real-time control and management, communication between CPUs in a hierarchical distributed control system is generally serial. Therefore, serial interfaces are commonly used in microcomputer application systems. Many peripherals and computers communicate serially, where serial communication refers to the method of information transfer between peripherals and interface circuits, while the CPU and interface still operate in parallel.
Serial Port: A serial port is a very common communication protocol for device communication on a computer, and should not be confused with Universal Serial Bus (USB). Most computers include two RS232-based serial ports. The serial port is also a common communication protocol for instruments and devices; many GPIB-compatible devices also have RS-232 ports. Additionally, the serial communication protocol can also be used to retrieve data from remote collection devices.
The concept of serial communication is very simple: the serial port sends and receives bytes bit by bit. Although it is slower than parallel communication, which sends data byte by byte, the serial port can send data on one line while receiving data on another. It is simple and can achieve long-distance communication. For example, when IEEE488 defines the parallel communication state, it stipulates that the total length of device lines must not exceed 20 meters, and the length between any two devices must not exceed 2 meters; whereas for serial ports, the length can reach 1200 meters.
Typically, serial ports are used for the transmission of ASCII characters. Communication is completed using three lines: ground, transmit, and receive. Since serial communication is asynchronous, the port can send data on one line while receiving data on another. Other lines are used for handshaking but are not mandatory. The most important parameters of serial communication are baud rate, data bits, stop bits, and parity. For two ports communicating, these parameters must match:
a. Baud Rate: This is a parameter that measures communication speed. It indicates the number of bits transmitted per second. For example, 300 baud means 300 bits are sent per second. When we refer to clock cycles, we are referring to the baud rate. For instance, if a protocol requires a baud rate of 4800, the clock is 4800Hz. This means that the sampling rate for serial communication on the data line is 4800Hz. Typically, telephone lines have baud rates of 14400, 28800, and 36600. Baud rates can be much higher than these values, but baud rate is inversely proportional to distance. High baud rates are often used for communication between instruments placed very close together, a typical example being GPIB device communication.
b. Data Bits: This parameter measures the actual data bits in communication. When a computer sends a packet, the actual data may not be 8 bits; the standard values are 5, 7, and 8 bits. How this is set depends on the information you want to transmit. For example, standard ASCII code is 0–127 (7 bits). Extended ASCII code is 0–255 (8 bits). If the data uses simple text (standard ASCII code), then each data packet uses 7 bits of data. Each packet refers to a byte that includes start/stop bits, data bits, and parity bits. Since the actual data bits depend on the choice of communication protocol, the term ‘packet’ refers to any communication situation.
c. Stop Bits: Used to indicate the last bit of a single packet. Typical values are 1, 1.5, and 2 bits. Since data is timed on the transmission line, and each device has its own clock, it is likely that a slight desynchronization occurs between two devices during communication. Therefore, stop bits not only indicate the end of transmission but also provide the opportunity for computers to correct clock synchronization. The more stop bits applicable, the greater the tolerance for desynchronization, but the data transmission rate also becomes slower.
d. Parity Bit: A simple error detection method in serial communication. There are four types of error detection: even, odd, high, and low. Of course, it is also possible to have no parity bit. For even and odd parity, the serial port will set a parity bit (one bit after the data bits) with a value to ensure that the number of logic high bits transmitted is even or odd. For example, if the data is 011, for even parity, the parity bit is 0, ensuring that the number of logic high bits is even. If it is odd parity, the parity bit is 1, resulting in three logic high bits. High and low bits do not actually check the data; they simply set the logic high or low for checking. This allows the receiving device to know the state of a bit and have the opportunity to determine whether noise has interfered with communication or whether the transmission and reception of data are unsynchronized.
In 1971, Modicon first introduced the Modbus protocol, with Modbus RTU and Modbus ASCII born from it. Later, Schneider Electric acquired Modicon and launched the Modbus TCP protocol in 1997. In 2004, the National Standardization Administration of China officially recognized Modbus as a national standard, marking the beginning of Modbus’s contribution to industrial communication in China.
Through this protocol, controllers can communicate with each other, and controllers can communicate with other devices via the network. Modbus protocol is characterized by being standard, open, supporting multiple electrical interfaces, having a simple and compact data frame format, large data transmission volume, and good real-time performance, making it widely used in industrial control systems and becoming a general industrial standard. An in-depth analysis of the Modbus protocol’s implementation principles and its security is of significant practical importance for enhancing the security of industrial control systems.
Modbus RTU and Modbus ASCII are mainly used in the field of serial communication, while Modbus TCP is commonly used in Ethernet communication. Today, Modbus has become the standard communication protocol in the industrial field and is now a commonly used connection method between industrial electronic devices.
Modbus uses a simple Master and Slave protocol (client/server protocol) for communication. The client acts as the master, sending requests to the server; the server (slave) receives the request, analyzes it, and responds. The communication frame used is called the Application Data Unit (ADU), which includes communication address segment, function code segment, data segment, and checksum segment, as shown in the figure below:
Typically, monitoring systems (HMI) serve as the Master, while PLCs, electric meters, and instruments serve as Slaves. The HMI system continuously polls various relays and registers for the latest values, then displays and processes them through various logical calculations and control adjustments.
Here, the function code segment and data segment combined are called the Protocol Data Unit (PDU). The function code segment occupies one byte, with a value range of 1-255, where 128-255 are reserved for exception message responses, while 1-127 are function code numbers, with 65-72 and 100-110 being user-defined codes.
The Modbus protocol is a message transmission protocol at the application layer, including three message types: ASCII, RTU, and TCP. The protocol itself does not define the physical layer; it only defines the message structure that controllers can recognize and use, regardless of the network used for communication.
When the Modbus protocol is transmitted over a serial port, it can choose either RTU or ASCII mode, specifying the message, data structure, commands, and response methods while requiring data verification. The ASCII mode uses LRC verification, while the RTU mode uses 16-bit CRC verification. When transmitted over Ethernet, TCP is used, and this mode does not use verification because the TCP protocol is a reliable connection-oriented protocol.
Modbus is an application layer protocol that defines data units (ADU) independent of the underlying network, allowing communication over Ethernet (TCP/IP) or serial links (RS232, RS485, etc.) (Ethernet ADU and serial ADU are slightly different). In serial links, the Modbus protocol has two transmission modes: ASCII mode and RTU mode. ASCII is the abbreviation for American Standard Code for Information Interchange, while RTU stands for Remote Terminal Unit.
First, let’s take a look at how Modbus works.
Modbus uses a master-slave communication mode, where only the master device can initiate transmission, and the slave device responds to the master’s request. Typical master devices include field instruments and display panels, while typical slave devices are Programmable Logic Controllers (PLCs).
In serial link master-slave communication, a Modbus master device can connect to one or N (up to 247) slave devices, and communication between master and slave devices includes both unicast and broadcast modes.
In broadcast mode, the Modbus master device can simultaneously send requests to multiple slave devices (device address 0 is used for broadcast mode), and slave devices do not respond to broadcast requests.
In unicast mode, the master device sends a request to a specific slave device (each Modbus slave device has a unique address), and the request message frame will contain function codes and data, such as function code “01” used to read the status of discrete coils. After receiving the request, the slave responds and feeds the message back to the master device.
In communication between master and slave devices, either ASCII mode or RTU mode can be used. In ASCII (American Standard Code for Information Interchange) transmission mode, the message frame starts with an English colon (“:”, ASCII 3A Hex) and ends with a carriage return and line feed (CRLF, ASCII 0D and 0A Hex), allowing a character set of hexadecimal 0-9 and A-F; the slave devices in the network monitor the transmission path for the English colon (“:”). If detected, they decode the message frame and check if the address in the message matches their own address; if it matches, they receive the data; if not, they ignore it.
In ASCII mode, each 8-bit byte is split into two ASCII characters for transmission. For example, the hexadecimal number 0xAF will be broken down into ASCII characters “A” and “F” for transmission, effectively doubling the amount of characters sent compared to RTU. The advantage of ASCII mode is that it allows for a gap of up to 1 second between two characters without causing communication failure, and this mode uses Longitudinal Redundancy Check (LRC) for error checking. When the controller is set to communicate over the Modbus network in RTU mode, each 8-bit byte in the message consists of two 4-bit hexadecimal characters, and there are no start and end markers. Its advantage is that more data can be transmitted at the same baud rate.
In RTU (Remote Terminal Unit) mode, each byte can transmit two hexadecimal characters, such as the hexadecimal number 0xAF, sent directly as hexadecimal 0xAF (binary: 10101111), resulting in a transmission density that is twice that of ASCII mode; RTU mode employs cyclic redundancy check (CRC), summarized in the following format:
The specific format is shown in the figure below:
6.1 Master and Slave, Server and Client
[In the Modbus protocol]
The master sends a Modbus request, and the slave responds based on the request content. In the Modbus protocol, the master is always the active party, and the slave is always the passive party.
[In network applications]
In network applications, there are clients and servers. The client (e.g., a browser) sends requests to the server, and the server returns content (e.g., HTML text) to the client.
[In Modbus TCP]
The master is the client, while the slave is the server. Do not think that the server is more important; the master is also important, so the master is the server.
6.2 Can There Be Multiple Masters?
From the previous analysis, since the master is the client, Modbus TCP supports multiple masters, allowing multiple masters and multiple slaves to exist in a local area network. The connection capacity of the slaves (the number of masters they can connect to) is determined by the maximum number of TCP connections supported by uIP.
6.3 Brief Overview of Modbus TCP Protocol
Modbus TCP is fundamentally similar to Modbus RTU but does have some differences:
a. The slave address becomes less important and is often ignored. In a sense, the slave address is replaced by the IP address;
b. CRC check becomes less important and can even be ignored. Since TCP packets already have checks, Modbus TCP simply cancels the CRC check to avoid redundancy.
The TCP mode was created to allow Modbus data to be smoothly transmitted over Ethernet, using TCP port 502. The protocol’s physical layer, data link layer, network layer, and transport layer are all based on TCP protocol, only at the application layer is the Modbus protocol modified and encapsulated; the receiving end unpacks the TCP packet to retrieve the original Modbus frame, then parses it according to the Modbus protocol specifications and repackages the returned data packet into the TCP protocol, sending it back to the sender. Unlike the data format transmitted over serial links, TCP mode removes additional addresses and checks, adding a message header, the specific format is shown in the figure below.
In Modbus TCP, there is an MBAP header that contains the following parts:
Field
Length
Description
Client
Server
Transmission Flag |
2 bytes |
MODBUS request and response transmission sequence number |
Generated by the client |
Copied by the server during response |
Protocol Flag |
2 bytes |
Modbus protocol defaults to 0 |
Generated by the client |
Copied by the server during response |
Length |
2 bytes |
Length of the remaining part |
Generated by the client |
Generated by the server during response |
Unit Flag |
1 byte |
Slave flag (slave address) |
Generated by the client |
Copied by the server during response |
Note:
a. The transmission flag can be understood as a sequence number to prevent MODBUS TCP communication misalignment, for example, a later response arriving at the master before an earlier one;
b. The unit flag can be understood as the slave address, which is no longer important.
6.4 Relationship Between Modbus TCP and TCP/IP
Modbus TCP can be understood as an application layer protocol that occurs over TCP. Since it is a TCP protocol, a complete MODBUS TCP message must include TCP headers, IP headers, and Ethernet headers.
The client initiating Modbus transaction processing creates the Modbus Application Data Unit. The function code (in the PDU) indicates to the server which operation will be executed.
The function code field of the Modbus data unit is encoded in one byte. The valid range is decimal 1-255 (128-255 are reserved for exception responses). When the client sends a message to the server, the function code field indicates which operation will be executed by the server.
The data field of the message sent from the client to the server includes additional information that the server uses to execute the operation defined by the function code. This field also includes addresses for discrete items and registers, the number of items to be processed, and the actual number of data bytes in the field.
In some requests, the data field may not exist; in this case, the server does not require any additional information. The function code merely indicates the operation.
Types of Function Codes:
Function codes are mainly divided into valid function codes, exception function codes, and error function codes. If a Modbus ADU is correctly received without any errors related to the requested Modbus function, the response data from the server to the client will contain the normal function code from the request. If there are errors related to the requested Modbus function, the response data will contain an exception code and an error code.
For example, the client can read the on/off status of a set of discrete outputs or inputs, or the user can read/write a set of register data content. When the server responds to the client, it uses the function code field to indicate a normal (no error) response or the occurrence of some error (known as an exception response). For a normal response, the server only responds to the original function code.
For an exception response, the server returns a code identical to that of the client, setting the most significant bit of the original function code to logic 1 and adding the exception code plus an error code to inform the client of the reason for the exception.
Valid Function Codes
There are over twenty valid function codes, but in general use, the eight most common ones are 1, 2, 3, 4, 5, 6, 15, and 16, along with two special uses, 20 and 21, which are General Reference Registers. Most Modbus devices do not provide this Register. The main control data on PLCs consists of the following four types. These eight function codes handle these control data, detailed as follows:
Four Types of Control Data:
DI: Digital Input (Discrete Input), one address one data bit, the user can only read its state and cannot modify it. Represented by one bit as On/Off, used to record the state of control signals, such as switches, contact points, motor operation, limit switches, etc. In PLCs, it is referred to as Input relay, input coil, etc.
DO: Digital Output (Coil Output), one address one data bit, the user can set or reset, and can read back the state. Represented by one bit as On/Off, used to output control signals to activate or stop motors, alarms, lights, etc. In PLCs, it is referred to as Output relay, Output coil, etc.
AI: Analog Input (Input Register), one address 16-bit data, the user can only read and cannot modify, represented as a 16 bits integer to record the value of control signals, such as temperature, flow, material quantity, speed, rotational speed, valve opening, liquid level, weight, etc. In PLCs, it is referred to as Input register.
AO: Analog Output (Holding Register), one address 16-bit data, the user can write and read back, represented as a 16 bits integer to output the numerical value of control signals, such as temperature, flow, speed, rotational speed, valve opening, feed quantity, etc. In PLCs, it is referred to as Output register, Holding register.
Modbus protocol is a typical industrial control network protocol, and studying its security is of great significance for enhancing the security of industrial control networks. Generally speaking, security issues of protocols can be divided into two types: one is security issues caused by the design and description of the protocol itself; the other is security issues caused by incorrect implementation of the protocol. Modbus protocol also has both of these issues.
8.1 Inherent Issues of the Modbus Protocol
The vast majority of industrial control protocols were designed primarily with functionality, efficiency, and reliability in mind, without considering security issues. The Modbus protocol is no exception, even though it has become a de facto industrial standard. From the previous principle analysis, we can see that its inherent security issues include: lack of authentication, authorization, encryption, and function code abuse.
(1) Lack of Authentication
The purpose of authentication is to ensure that the received information comes from a legitimate user; unauthorized users sending control commands to devices will not be executed. In the Modbus protocol communication process, there are no relevant definitions for authentication; attackers only need to find a legitimate address to establish a Modbus communication session using function codes, thereby disrupting the entire or part of the control process.
(2) Lack of Authorization
Authorization ensures that different privileged operations are performed by authenticated users with different permissions, significantly reducing the probability of operational errors and internal attacks. Currently, the Modbus protocol lacks a role-based access control mechanism, does not categorize users, and does not define user permissions, allowing any user to execute any function.
(3) Lack of Encryption
Encryption ensures that information between both parties during communication cannot be illegally obtained by third parties. In the Modbus protocol communication process, addresses and commands are all transmitted in plaintext, making it easy for attackers to capture and analyze data, providing convenience for attackers.
(4) Function Code Abuse
Function codes are an important aspect of the Modbus protocol, as nearly all communication includes function codes. Currently, function code abuse is a major factor leading to anomalies in Modbus networks. For example, illegal message lengths, short cycles of useless commands, incorrect message lengths, and delayed confirmation of exception codes can all lead to denial-of-service attacks.
8.2 Issues Arising from Protocol Implementation
Although the Modbus protocol has been widely used, developers implementing specific industrial control systems often lack security knowledge or fail to recognize security issues. This leads to various security vulnerabilities in systems using the Modbus protocol.
(1) Design Security Issues
Modbus system developers focus primarily on functional implementation issues, with security issues rarely considered during design. Design security refers to fully considering security during design to address various anomalies and illegal operations that may occur in Modbus systems. For example, if a node is maliciously controlled during communication and sends illegal data, the system needs to consider how to identify and handle such data.
(2) Buffer Overflow Vulnerabilities
Buffer overflow refers to the situation where data exceeds the capacity of the buffer being filled, leading to overflow data overwriting valid data. This is one of the most common and dangerous vulnerabilities in software development, which can lead to system crashes or be exploited by attackers to gain control of the system.
Modbus system developers often lack knowledge of secure development, resulting in many buffer overflow vulnerabilities. If exploited by malicious actors, this could lead to severe consequences.
(3) Modbus TCP Security Issues
Currently, the Modbus protocol can be implemented on general-purpose computers and operating systems, operating over TCP/IP to meet developmental needs. This means that the inherent security issues of TCP/IP protocols inevitably affect the security of industrial control networks. Common attack methods in the IP Internet, such as unauthorized data acquisition, man-in-the-middle attacks, denial-of-service, IP spoofing, and malware, can all impact the security of Modbus systems.
8.3 Security Recommendations
Currently, the security measures taken by Modbus systems are generally insufficient. Here, referencing information security industry research and combining it with the security issues of industrial control systems, several security recommendations are proposed that can effectively reduce the threats faced by industrial control systems.
(1) Start from the Source
Vulnerabilities in industrial control networks largely stem from issues that arise during their implementation. If security measures are integrated from the outset—through the design, development, internal testing, and deployment stages of the Modbus system, incorporating secure design, secure coding, and secure testing techniques—this can significantly eliminate security vulnerabilities and reduce the overall security risk of the Modbus system.
(2) Anomaly Behavior Detection
Anomalous behavior indicates potential threats, regardless of whether there are attackers. Therefore, developing dedicated anomaly detection devices for Modbus systems can greatly enhance the security of industrial control networks. For Modbus systems, it is essential first to analyze the various operational behaviors they exhibit, describing these behaviors using a six-tuple model based on “subject, location, time, access method, operation, object”; then analyze whether the behaviors are anomalous; ultimately deciding on measures such as logging or alerting.
(3) Security Audits
The security audit of Modbus involves in-depth decoding and analysis of protocol data, recording key information such as the time, location, operator, and operational behavior, thereby achieving security audit logging and auditing functions for Modbus systems, providing traceability for security incidents.
(4) Use of Network Security Devices
Utilizing intrusion prevention and firewall network security devices. A firewall is a serial device that, through settings, only allows specific addresses to access the server while blocking external addresses from accessing the Modbus server, effectively preventing external intrusions; intrusion prevention devices can analyze the specific operational content of the Modbus protocol, effectively detecting and blocking anomalous operations and various penetration attacks from both internal and external sources, providing protection for the internal network.
Complete Question Bank for the 2021 Electrician Junior Exam (includes answers)
Is troubleshooting inverter faults difficult? Just one click!
Can you brush through all electrical exam questions with just one click? This tool is something you don’t want to miss!
Which of the five major electrical drawing software (CAD, Eplan, CADe_simu…) do you pick?
Latest electrical version CAD drawing software, with super detailed installation tutorial!
Latest electrical drawing software EPLAN, with super detailed installation tutorial!
Common issues for beginners using S7-200 SMART programming software (includes download links)
Comprehensive electrical calculation EXCEL spreadsheet, automatically generated! No need to seek help for electrical calculations!
Bluetooth headphones, electrician/PLC introductory books given away? Come and claim your electrical gifts!
Basic skills in PLC programming: Ladder diagrams and control circuits (with 1164 practical cases of Mitsubishi PLC)
Don’t understand electrical diagrams? Take away the basics of electrician diagram reading and simulation software, and quickly get hands-on!
12 free electrician video courses, 10GB software/e-books, and 30 days of free live electrician courses are being given away!
