Marcio Cunha

Modbus TCP Traffic Inspection with eBPF: Monitoring Layer 7 in Industrial Networks

Discover how to leverage eBPF technology to inspect Layer 7 packets in industrial networks, detecting anomalous Modbus TCP commands in real time without modifying applications or causing performance bottlenecks.

Marcio Cunha•7 min
Also available in:PortuguêsEspañol
Summary
  • The eBPF technology executes secure code directly inside the operating system kernel without modifying original binaries or loading external modules.
  • The Modbus TCP protocol operates without native encryption, leaving environments vulnerable if Layer 7 traffic remains unmonitored.
  • eBPF-based sensors capture read and write requests targeting industrial registers before malicious instructions reach programmable controllers.
  • Kernel-level payload inspection drastically reduces computational overhead compared to traditional user-space packet analysis solutions.
  • Successful implementation requires prior mapping of trusted IP addresses and strict constraints on unauthorized write functions.

The Visibility Challenge in Industrial Networks

Modern industrial networks face an invisible pressure: connecting the factory floor to the corporate world without opening doors for intrusions. In the past, industrial machinery and computers lived on isolated islands protected solely by obscurity. Today, automation systems converse with the cloud, databases analyze energy consumption in real time, and engineering teams access PLCs (Programmable Logic Controllers, which are the rugged computers responsible for triggering motors and valves) from anywhere in the world. This openness has driven operational agility, but it has also exposed vulnerabilities to sophisticated cyber threats that exploit legacy protocols designed in an era when security was not a priority.

In practice, this means any intruder with access to the corporate network can theoretically send malicious commands directly to physical equipment, altering boiler temperatures or halting entire assembly lines. The major obstacle for security teams is seeing what happens inside those network cables. Traditional network monitoring tools usually look only at IP addresses and connection ports without understanding the 'language' spoken by the machines. To mitigate this risk surgically, modern engineers are turning to an innovative low-level monitoring technology capable of reading the exact content of messages exchanged between supervisory systems and factory floor hardware.

Understanding eBPF as a Network Inspection Tool

eBPF, which stands for Extended Berkeley Packet Filter (a mechanism allowing custom code to run safely inside the operating system kernel), has sparked a revolution in the Linux universe. Think of it as a small, highly specialized robot living right at the heart of the operating system, the exact place where data packets arrive from the network interface card. Whenever a piece of information enters or leaves the computer, this robot can examine it instantly without copying data to external programs or slowing down normal machine flow. In network engineering, this eliminates the classic bottleneck where monitoring software had to pull all traffic into the application layer, consuming memory and delaying packet delivery.

When we apply this capability to the industrial domain, eBPF transforms from a generic diagnostic tool into an ultra-fast digital bodyguard. It intercepts network packets precisely at the moment they enter the network card, analyzes the initial bytes, and decides whether the content is legitimate or suspicious. Unlike traditional firewalls that block entire ports, eBPF can look inside the message and understand the context of communication. This paves the way for deep packet inspection directly at Layer 7, the application layer of the network model where specific industrial software commands reside, all running with performance close to raw network hardware.

Anatomy of a Modbus TCP Attack and Layer 7

To protect an industrial network, one must first understand the language it speaks. Modbus TCP is one of the oldest and most widely adopted communication protocols in automation, used to connect supervisory systems (SCADA) to sensors and actuators over standard Ethernet networks. The beauty of Modbus TCP lies in its minimalist simplicity: it operates on a straightforward request-response model. A master system sends a command asking to read a register (for example, 'what is the current tank pressure?') or to write a value (for example, 'adjust the valve to 50%'). The protocol's great Achilles' heel is the total absence of native encryption and authentication. If someone intercepts or injects a message, the PLC will obey blindly without questioning the sender's identity.

In practice, Layer 7 inspection means our security system must translate the raw bytes traveling across the network to understand exactly which Modbus function is being invoked. A Modbus TCP message carries its own header followed by the function code and register address data. Functions like reading discrete inputs (code 0x02) are relatively harmless, but multi-register write functions (code 0x10) have the power to alter vital operational parameters. If a write command arrives outside an approved maintenance window or from an IP address not belonging to the official engineering station, we are facing anomalous behavior. It is precisely this behavioral pattern we need to detect before physical damage occurs on the plant floor.

Implementing an eBPF Program for Command Capture

Writing an eBPF program requires specialized tools like Clang and LLVM to compile C code into a safe bytecode format that the Linux kernel can verify and execute. The following code illustrates a simplified structure designed to be injected into the kernel's network hook (tc - traffic control), intercepting traffic destined for the default Modbus TCP port 502 and checking for suspicious write function codes.

#include <linux/bpf.h> #include <linux/if_ether.h> #include <linux/ip.h> #include <linux/tcp.h> #include <bpf/bpf_helpers.h>  #define MODBUS_PORT 502 #define MBAP_HEADER_LEN 7  SEC("tc") int parse_modbus_tcp(struct __sk_buff *ctx) {     void *data = (void *)(long)ctx->data;     void *data_end = (void *)(long)ctx->data_end;      struct ethhdr *eth = data;     if ((void *)(eth + 1) > data_end) return TC_ACT_OK;      if (eth->h_proto != __constant_htons(ETH_P_IP)) return TC_ACT_OK;      struct iphdr *ip = (void *)(eth + 1);     if ((void *)(ip + 1) > data_end) return TC_ACT_OK;      if (ip->protocol != IPPROTO_TCP) return TC_ACT_OK;      struct tcphdr *tcp = (void *)ip + (ip->ihl * 4);     if ((void *)(tcp + 1) > data_end) return TC_ACT_OK;      if (tcp->dest != __constant_htons(MODBUS_PORT)) return TC_ACT_OK;      char *payload = (char *)(tcp + 1);     if ((void *)(payload + MBAP_HEADER_LEN + 1) > data_end) return TC_ACT_OK;      // Modbus function code is located right after the 7-byte MBAP header     __u8 function_code = payload[MBAP_HEADER_LEN];      // Write functions (e.g., 0x06 for single write, 0x10 for multiple write)     if (function_code == 0x06 || function_code == 0x10) {         bpf_trace_printk("Modbus Alert: Write command detected at Layer 7! Code: %d\n", function_code);     }      return TC_ACT_OK; }  char _license[] CSEC("license") = "GPL"; 

This program operates directly in the network packet path, analyzing Ethernet, IP, and TCP headers within microseconds. Upon identifying port 502, it advances to the payload, extracts the byte corresponding to the Modbus function, and triggers an alert if a write instruction is found. This approach monitors industrial traffic with surgical precision, adding no perceptible latency to PLCs and requiring no changes to existing physical infrastructure.

Operational Validation and False Positive Management

Deploying deep packet inspection in an industrial production environment demands discipline and rigorous testing to avoid unwanted operational disruptions. The first practical step consists of running the eBPF filter in strictly passive mode, solely collecting metrics and logging alerts without dropping any packets. During this observation phase, which should last at least a few weeks, the engineering team maps standard network behavior, identifying which supervisory software sends which types of commands and at what times. This learning period is essential to separate legitimate operational noise from actual intrusion attempts.

In practice, the biggest operational challenge is often dealing with legitimate diagnostic tools that engineers use daily to calibrate sensors. Frequently, a technician opens configuration software to update parameters across dozens of PLCs simultaneously, generating a flood of write commands that mimic cyber-attack behavior. To resolve this dilemma, Layer 7 inspection rules must integrate with whitelists based on trusted network identities or operational context tokens. Thus, the system learns to differentiate an authorized operator performing scheduled maintenance from an external intruder attempting to inject arbitrary commands in the dead of night.

Final Considerations

Industrial network security is no longer a problem solved solely by physically isolating machinery. With the growing integration between IT and automation systems, ensuring data integrity at Layer 7 has become an imperative necessity for business continuity. Adopting eBPF to inspect Modbus TCP traffic in real time represents a remarkable evolutionary leap, combining the extreme performance demanded by the factory floor with the granular visibility indispensable for modern cyber defense.

By deploying intelligent filters directly inside the operating system kernel, organizations can detect anomalous commands and tampering attempts before physical damage occurs to equipment. The secret to success on this journey lies in the careful balance between security automation, deep understanding of legacy protocols, and close collaboration between networking and industrial engineering teams. Protecting the future of industry requires looking inside data packets with the same care we give to the physical infrastructure sustaining our society.